mmgp 1.0.5__tar.gz → 1.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mmgp might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mmgp
3
- Version: 1.0.5
3
+ Version: 1.0.6
4
4
  Summary: Memory Management for the GPU Poor
5
5
  Author-email: deepbeepmeep <deepbeepmeep@yahoo.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -683,7 +683,11 @@ License-File: LICENSE.md
683
683
  Requires-Dist: torch>=2.1.0
684
684
  Requires-Dist: optimum-quanto
685
685
 
686
- **------------------ Memory Management for the GPU Poor by DeepBeepMeep ------------------**
686
+
687
+ <p align="center">
688
+ <H2>Memory Management for the GPU Poor by DeepBeepMeep</H2>
689
+ </p>
690
+
687
691
 
688
692
  This module contains multiples optimisations so that models such as Flux (and derived), Mochi, CogView, HunyuanVideo, ... can run smoothly on a 24 GB GPU limited card.
689
693
  This a replacement for the accelerate library that should in theory manage offloading, but doesn't work properly with models that are loaded / unloaded several
@@ -693,31 +697,50 @@ Requirements:
693
697
  - GPU: RTX 3090/ RTX 4090 (24 GB of VRAM)
694
698
  - RAM: minimum 48 GB, recommended 64 GB
695
699
 
700
+ First you need to install the module in your current project with:
701
+ ```shell
702
+ pip install mmgp
703
+ ```
704
+
696
705
  It is almost plug and play and just needs to be invoked from the main app just after the model pipeline has been created.
697
- 1) First make sure that the pipeline explictly loads the models in the CPU device
698
- for instance: pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
706
+ 1) First make sure that the pipeline explictly loads the models in the CPU device, for instance:
707
+ ```
708
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
709
+ ```
710
+
699
711
  2) Once every potential Lora has been loaded and merged, add the following lines:
700
712
 
701
- *from mmgp import offload*
702
- *offload.me(pipe)*
703
-
704
- The 'transformer' model that contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
713
+ ```
714
+ from mmgp import offload
715
+ offload.me(pipe)
716
+ ```
717
+ The 'transformer' model in the pipe contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
705
718
 
706
719
  If you have more than 64GB RAM you may want to enable RAM pinning with the option *pinInRAM = True*. You will get in return super fast loading / unloading of models
707
720
  (this can save significant time if the same pipeline is run multiple times in a row)
708
721
 
709
- Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.
710
-
722
+ Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.\
711
723
  For instance :
712
- for flux derived models: *pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }*
713
- for mochi: *pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }*
724
+
725
+
726
+ - for flux derived models:
727
+ ```
728
+ pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }
729
+ ```
730
+ - for mochi:
731
+ ```
732
+ pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }
733
+ ```
734
+
714
735
 
715
736
  Please note that there should be always one model whose Id is 'transformer'. It corresponds to the main image / video model which usually needs to be quantized (this is done on the fly by default when loading the model).
716
737
 
717
738
  Becareful, lots of models use the T5 XXL as a text encoder. However, quite often their corresponding pipeline configurations point at the official Google T5 XXL repository
718
739
  where there is a huge 40GB model to download and load. It is cumbersorme as it is a 32 bits model and contains the decoder part of T5 that is not used.
719
740
  I suggest you use instead one of the 16 bits encoder only version available around, for instance:
720
- *text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)*
741
+ ```
742
+ text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)
743
+ ```
721
744
 
722
745
  Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
723
746
  - For instance you may need to disable an existing CPU offload logic that already exists (such as manual calls to move tensors between cuda and the cpu)
@@ -727,6 +750,6 @@ You are free to use my module for non commercial use as long you give me proper
727
750
 
728
751
  Thanks to
729
752
  ---------
730
- Huggingface / accelerate for the hooking examples
731
- Huggingface / quanto for their very useful quantizer
732
- gau-nernst for his Pinnig RAM samples
753
+ - Huggingface / accelerate for the hooking examples
754
+ - Huggingface / quanto for their very useful quantizer
755
+ - gau-nernst for his Pinnig RAM samples
@@ -1,4 +1,8 @@
1
- **------------------ Memory Management for the GPU Poor by DeepBeepMeep ------------------**
1
+
2
+ <p align="center">
3
+ <H2>Memory Management for the GPU Poor by DeepBeepMeep</H2>
4
+ </p>
5
+
2
6
 
3
7
  This module contains multiples optimisations so that models such as Flux (and derived), Mochi, CogView, HunyuanVideo, ... can run smoothly on a 24 GB GPU limited card.
4
8
  This a replacement for the accelerate library that should in theory manage offloading, but doesn't work properly with models that are loaded / unloaded several
@@ -8,31 +12,50 @@ Requirements:
8
12
  - GPU: RTX 3090/ RTX 4090 (24 GB of VRAM)
9
13
  - RAM: minimum 48 GB, recommended 64 GB
10
14
 
15
+ First you need to install the module in your current project with:
16
+ ```shell
17
+ pip install mmgp
18
+ ```
19
+
11
20
  It is almost plug and play and just needs to be invoked from the main app just after the model pipeline has been created.
12
- 1) First make sure that the pipeline explictly loads the models in the CPU device
13
- for instance: pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
21
+ 1) First make sure that the pipeline explictly loads the models in the CPU device, for instance:
22
+ ```
23
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
24
+ ```
25
+
14
26
  2) Once every potential Lora has been loaded and merged, add the following lines:
15
27
 
16
- *from mmgp import offload*
17
- *offload.me(pipe)*
18
-
19
- The 'transformer' model that contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
28
+ ```
29
+ from mmgp import offload
30
+ offload.me(pipe)
31
+ ```
32
+ The 'transformer' model in the pipe contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
20
33
 
21
34
  If you have more than 64GB RAM you may want to enable RAM pinning with the option *pinInRAM = True*. You will get in return super fast loading / unloading of models
22
35
  (this can save significant time if the same pipeline is run multiple times in a row)
23
36
 
24
- Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.
25
-
37
+ Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.\
26
38
  For instance :
27
- for flux derived models: *pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }*
28
- for mochi: *pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }*
39
+
40
+
41
+ - for flux derived models:
42
+ ```
43
+ pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }
44
+ ```
45
+ - for mochi:
46
+ ```
47
+ pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }
48
+ ```
49
+
29
50
 
30
51
  Please note that there should be always one model whose Id is 'transformer'. It corresponds to the main image / video model which usually needs to be quantized (this is done on the fly by default when loading the model).
31
52
 
32
53
  Becareful, lots of models use the T5 XXL as a text encoder. However, quite often their corresponding pipeline configurations point at the official Google T5 XXL repository
33
54
  where there is a huge 40GB model to download and load. It is cumbersorme as it is a 32 bits model and contains the decoder part of T5 that is not used.
34
55
  I suggest you use instead one of the 16 bits encoder only version available around, for instance:
35
- *text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)*
56
+ ```
57
+ text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)
58
+ ```
36
59
 
37
60
  Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
38
61
  - For instance you may need to disable an existing CPU offload logic that already exists (such as manual calls to move tensors between cuda and the cpu)
@@ -42,6 +65,6 @@ You are free to use my module for non commercial use as long you give me proper
42
65
 
43
66
  Thanks to
44
67
  ---------
45
- Huggingface / accelerate for the hooking examples
46
- Huggingface / quanto for their very useful quantizer
47
- gau-nernst for his Pinnig RAM samples
68
+ - Huggingface / accelerate for the hooking examples
69
+ - Huggingface / quanto for their very useful quantizer
70
+ - gau-nernst for his Pinnig RAM samples
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "mmgp"
3
+ version = "1.0.6"
4
+ authors = [
5
+ { name = "deepbeepmeep", email = "deepbeepmeep@yahoo.com" },
6
+ ]
7
+ description = "Memory Management for the GPU Poor"
8
+ readme = "README.md"
9
+ requires-python = ">=3.10"
10
+ license = { file = "LICENSE.md" }
11
+ dependencies = [
12
+ "torch >= 2.1.0",
13
+ "optimum-quanto",
14
+ ]
15
+
16
+ [tool.setuptools.packages.find]
17
+ # All the following settings are optional:
18
+ where = ["src"]
19
+ namespaces = false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mmgp
3
- Version: 1.0.5
3
+ Version: 1.0.6
4
4
  Summary: Memory Management for the GPU Poor
5
5
  Author-email: deepbeepmeep <deepbeepmeep@yahoo.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -683,7 +683,11 @@ License-File: LICENSE.md
683
683
  Requires-Dist: torch>=2.1.0
684
684
  Requires-Dist: optimum-quanto
685
685
 
686
- **------------------ Memory Management for the GPU Poor by DeepBeepMeep ------------------**
686
+
687
+ <p align="center">
688
+ <H2>Memory Management for the GPU Poor by DeepBeepMeep</H2>
689
+ </p>
690
+
687
691
 
688
692
  This module contains multiples optimisations so that models such as Flux (and derived), Mochi, CogView, HunyuanVideo, ... can run smoothly on a 24 GB GPU limited card.
689
693
  This a replacement for the accelerate library that should in theory manage offloading, but doesn't work properly with models that are loaded / unloaded several
@@ -693,31 +697,50 @@ Requirements:
693
697
  - GPU: RTX 3090/ RTX 4090 (24 GB of VRAM)
694
698
  - RAM: minimum 48 GB, recommended 64 GB
695
699
 
700
+ First you need to install the module in your current project with:
701
+ ```shell
702
+ pip install mmgp
703
+ ```
704
+
696
705
  It is almost plug and play and just needs to be invoked from the main app just after the model pipeline has been created.
697
- 1) First make sure that the pipeline explictly loads the models in the CPU device
698
- for instance: pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
706
+ 1) First make sure that the pipeline explictly loads the models in the CPU device, for instance:
707
+ ```
708
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
709
+ ```
710
+
699
711
  2) Once every potential Lora has been loaded and merged, add the following lines:
700
712
 
701
- *from mmgp import offload*
702
- *offload.me(pipe)*
703
-
704
- The 'transformer' model that contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
713
+ ```
714
+ from mmgp import offload
715
+ offload.me(pipe)
716
+ ```
717
+ The 'transformer' model in the pipe contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option *quantizeTransformer* to *False* to turn off on the fly quantization.
705
718
 
706
719
  If you have more than 64GB RAM you may want to enable RAM pinning with the option *pinInRAM = True*. You will get in return super fast loading / unloading of models
707
720
  (this can save significant time if the same pipeline is run multiple times in a row)
708
721
 
709
- Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.
710
-
722
+ Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.\
711
723
  For instance :
712
- for flux derived models: *pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }*
713
- for mochi: *pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }*
724
+
725
+
726
+ - for flux derived models:
727
+ ```
728
+ pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }
729
+ ```
730
+ - for mochi:
731
+ ```
732
+ pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }
733
+ ```
734
+
714
735
 
715
736
  Please note that there should be always one model whose Id is 'transformer'. It corresponds to the main image / video model which usually needs to be quantized (this is done on the fly by default when loading the model).
716
737
 
717
738
  Becareful, lots of models use the T5 XXL as a text encoder. However, quite often their corresponding pipeline configurations point at the official Google T5 XXL repository
718
739
  where there is a huge 40GB model to download and load. It is cumbersorme as it is a 32 bits model and contains the decoder part of T5 that is not used.
719
740
  I suggest you use instead one of the 16 bits encoder only version available around, for instance:
720
- *text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)*
741
+ ```
742
+ text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)
743
+ ```
721
744
 
722
745
  Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
723
746
  - For instance you may need to disable an existing CPU offload logic that already exists (such as manual calls to move tensors between cuda and the cpu)
@@ -727,6 +750,6 @@ You are free to use my module for non commercial use as long you give me proper
727
750
 
728
751
  Thanks to
729
752
  ---------
730
- Huggingface / accelerate for the hooking examples
731
- Huggingface / quanto for their very useful quantizer
732
- gau-nernst for his Pinnig RAM samples
753
+ - Huggingface / accelerate for the hooking examples
754
+ - Huggingface / quanto for their very useful quantizer
755
+ - gau-nernst for his Pinnig RAM samples
@@ -1,9 +1,6 @@
1
1
  LICENSE.md
2
2
  README.md
3
3
  pyproject.toml
4
- src/__init__.py
5
- src/_version.py
6
- src/mmgp.py
7
4
  src/mmgp.egg-info/PKG-INFO
8
5
  src/mmgp.egg-info/SOURCES.txt
9
6
  src/mmgp.egg-info/dependency_links.txt
@@ -0,0 +1 @@
1
+
mmgp-1.0.5/pyproject.toml DELETED
@@ -1,74 +0,0 @@
1
- [project]
2
- name = "mmgp"
3
- authors = [
4
- { name = "deepbeepmeep", email = "deepbeepmeep@yahoo.com" },
5
- ]
6
- description = "Memory Management for the GPU Poor"
7
- readme = "README.md"
8
- requires-python = ">=3.10"
9
- license = { file = "LICENSE.md" }
10
- dynamic = ["version"]
11
- dependencies = [
12
- "torch >= 2.1.0",
13
- "optimum-quanto",
14
- ]
15
-
16
- [project.optional-dependencies]
17
-
18
-
19
- [build-system]
20
- build-backend = "setuptools.build_meta"
21
- requires = ["setuptools>=64", "wheel", "setuptools_scm>=8"]
22
-
23
- [tool.ruff]
24
- line-length = 110
25
- target-version = "py310"
26
- extend-exclude = ["/usr/lib/*"]
27
-
28
- [tool.ruff.lint]
29
- ignore = [
30
- "E501", # line too long - will be fixed in format
31
- ]
32
-
33
- [tool.ruff.format]
34
- quote-style = "double"
35
- indent-style = "space"
36
- line-ending = "auto"
37
- skip-magic-trailing-comma = false
38
- docstring-code-format = true
39
- exclude = [
40
- "src/_version.py", # generated by setuptools_scm
41
- ]
42
-
43
- [tool.ruff.lint.isort]
44
- combine-as-imports = true
45
- force-wrap-aliases = true
46
- known-local-folder = ["src"]
47
- known-first-party = ["mmgp"]
48
-
49
- [tool.pyright]
50
- include = ["src"]
51
- exclude = [
52
- "**/__pycache__", # cache directories
53
- "./typings", # generated type stubs
54
- ]
55
- stubPath = "./typings"
56
-
57
- [tool.tomlsort]
58
- in_place = true
59
- no_sort_tables = true
60
- spaces_before_inline_comment = 1
61
- spaces_indent_inline_array = 2
62
- trailing_comma_inline_array = true
63
- sort_first = [
64
- "project",
65
- "build-system",
66
- "tool.setuptools",
67
- ]
68
-
69
- # needs to be last for CI reasons
70
- [tool.setuptools_scm]
71
- write_to = "src/_version.py"
72
- parentdir_prefix_version = "mmgp-"
73
- fallback_version = "1.0.5"
74
- version_scheme = "post-release"
File without changes
@@ -1,16 +0,0 @@
1
- # file generated by setuptools_scm
2
- # don't change, don't track in version control
3
- TYPE_CHECKING = False
4
- if TYPE_CHECKING:
5
- from typing import Tuple, Union
6
- VERSION_TUPLE = Tuple[Union[int, str], ...]
7
- else:
8
- VERSION_TUPLE = object
9
-
10
- version: str
11
- __version__: str
12
- __version_tuple__: VERSION_TUPLE
13
- version_tuple: VERSION_TUPLE
14
-
15
- __version__ = version = '1.0.5'
16
- __version_tuple__ = version_tuple = (1, 0, 5)
@@ -1,3 +0,0 @@
1
- __init__
2
- _version
3
- mmgp
mmgp-1.0.5/src/mmgp.py DELETED
@@ -1,415 +0,0 @@
1
- # ------------------ Memory Management for the GPU Poor by DeepBeepMeep (mmgp)------------------
2
- #
3
- # This module contains multiples optimisations so that models such as Flux (and derived), Mochi, CogView, HunyuanVideo, ... can run smoothly on a 24 GB GPU limited card.
4
- # This a replacement for the accelerate library that should in theory manage offloading, but doesn't work properly with models that are loaded / unloaded several
5
- # times in a pipe (eg VAE).
6
- #
7
- # Requirements:
8
- # - GPU: RTX 3090/ RTX 4090 (24 GB of VRAM)
9
- # - RAM: minimum 48 GB, recommended 64 GB
10
- #
11
- # It is almost plug and play and just needs to be invoked from the main app just after the model pipeline has been created.
12
- # 1) First make sure that the pipeline explictly loads the models in the CPU device
13
- # for instance: pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
14
- # 2) Once every potential Lora has been loaded and merged, add the following lines:
15
- # from mmgp import offload
16
- # offload.me(pipe)
17
- # The 'transformer' model that contains usually the video or image generator is quantized on the fly by default to 8 bits. If you want to save time on disk and reduce the loading time, you may want to load directly a prequantized model. In that case you need to set the option quantizeTransformer to False to turn off on the fly quantization.
18
- #
19
- # If you have more than 64GB RAM you may want to enable RAM pinning with the option pinInRAM = True. You will get in return super fast loading / unloading of models
20
- # (this can save significant time if the same pipeline is run multiple times in a row)
21
- #
22
- # Sometime there isn't an explicit pipe object as each submodel is loaded separately in the main app. If this is the case, you need to create a dictionary that manually maps all the models.
23
- #
24
- # For instance :
25
- # for flux derived models: pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }
26
- # for mochi: pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }
27
- #
28
- # Please note that there should be always one model whose Id is 'transformer'. It corresponds to the main image / video model which usually needs to be quantized (this is done on the fly by default when loading the model)
29
- #
30
- # Becareful, lots of models use the T5 XXL as a text encoder. However, quite often their corresponding pipeline configurations point at the official Google T5 XXL repository
31
- # where there is a huge 40GB model to download and load. It is cumbersorme as it is a 32 bits model and contains the decoder part of T5 that is not used.
32
- # I suggest you use instead one of the 16 bits encoder only version available around, for instance:
33
- # text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)
34
- #
35
- # Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
36
- # - For instance you may need to disable an existing CPU offload logic that already exists (such as manual calls to move tensors between cuda and the cpu)
37
- # - mmpg to tries to fake the device as being "cuda" but sometimes some code won't be fooled and it will create tensors in the cpu device and this may cause some issues.
38
- #
39
- # You are free to use my module for non commercial use as long you give me proper credits. You may contact me on twitter @deepbeepmeep
40
- #
41
- # Thanks to
42
- # ---------
43
- # Huggingface / accelerate for the hooking examples
44
- # Huggingface / quanto for their very useful quantizer
45
- # gau-nernst for his Pinnig RAM samples
46
-
47
-
48
- #
49
- import torch
50
- #
51
- import gc
52
- import time
53
- import functools
54
- from optimum.quanto import freeze, qfloat8, qint8, quantize, QModuleMixin, QTensor
55
-
56
-
57
-
58
- cotenants_map = {
59
- "text_encoder": ["vae", "text_encoder_2"],
60
- "text_encoder_2": ["vae", "text_encoder"],
61
- }
62
-
63
- # useful functions to move a group of tensors (to design custom offload patches)
64
- def move_tensors(obj, device):
65
- if torch.is_tensor(obj):
66
- return obj.to(device)
67
- elif isinstance(obj, dict):
68
- _dict = {}
69
- for k, v in obj.items():
70
- _dict[k] = move_tensors(v, device)
71
- return _dict
72
- elif isinstance(obj, list):
73
- _list = []
74
- for v in obj:
75
- _list.append(move_tensors(v, device))
76
- return _list
77
- else:
78
- raise TypeError("Tensor or list / dict of tensors expected")
79
-
80
-
81
- def get_model_name(model):
82
- return model.name
83
-
84
- class HfHook:
85
- def __init__(self):
86
- self.execution_device = "cuda"
87
-
88
- def detach_hook(self, module):
89
- pass
90
-
91
- class offload:
92
- def __init__(self):
93
- self.active_models = []
94
- self.active_models_ids = []
95
- self.models = {}
96
- self.verbose = False
97
- self.models_to_quantize = []
98
- self.pinned_modules_data = {}
99
- self.params_of_modules = {}
100
- self.pinTensors = False
101
- self.device_mem_capacity = torch.cuda.get_device_properties(0).total_memory
102
- self.last_reserved_mem_check =0
103
-
104
- def collect_module_parameters(self, module: torch.nn.Module, module_params):
105
- if isinstance(module, (torch.nn.ModuleList, torch.nn.Sequential)):
106
- for i in range(len(module)):
107
- current_layer = module[i]
108
- module_params.extend(current_layer.parameters())
109
- module_params.extend(current_layer.buffers())
110
- else:
111
- for p in module.parameters(recurse=False):
112
- module_params.append(p)
113
- for p in module.buffers(recurse=False):
114
- module_params.append(p)
115
- for sub_module in module.children():
116
- self.collect_module_parameters(sub_module, module_params)
117
-
118
- def can_model_be_cotenant(self, model_id):
119
- potential_cotenants= cotenants_map.get(model_id, None)
120
- if potential_cotenants is None:
121
- return False
122
- for existing_cotenant in self.active_models_ids:
123
- if existing_cotenant not in potential_cotenants:
124
- return False
125
- return True
126
-
127
- def gpu_load(self, model_id):
128
- model = self.models[model_id]
129
- self.active_models.append(model)
130
- self.active_models_ids.append(model_id)
131
- if self.verbose:
132
- model_name = model._get_name()
133
- print(f"Loading model {model_name} ({model_id}) in GPU")
134
- if not self.pinInRAM:
135
- model.to("cuda")
136
- else:
137
- module_params = self.params_of_modules[model_id]
138
- for p in module_params:
139
- if isinstance(p, QTensor):
140
- p._data = p._data.cuda(non_blocking=True)
141
- p._scale = p._scale.cuda(non_blocking=True)
142
- else:
143
- p.data = p.data.cuda(non_blocking=True) #
144
- # torch.cuda.current_stream().synchronize()
145
- @torch.compiler.disable()
146
- def unload_all(self):
147
- for model, model_id in zip(self.active_models, self.active_models_ids):
148
- if not self.pinInRAM:
149
- model.to("cpu")
150
- else:
151
- module_params = self.params_of_modules[model_id]
152
- pinned_parameters_data = self.pinned_modules_data[model_id]
153
- for p in module_params:
154
- if isinstance(p, QTensor):
155
- data = pinned_parameters_data[p]
156
- p._data = data[0]
157
- p._scale = data[1]
158
- else:
159
- p.data = pinned_parameters_data[p]
160
-
161
-
162
- self.active_models = []
163
- self.active_models_ids = []
164
- torch.cuda.empty_cache()
165
- gc.collect()
166
-
167
- def move_args_to_gpu(self, *args, **kwargs):
168
- new_args= []
169
- new_kwargs={}
170
- for arg in args:
171
- if torch.is_tensor(arg):
172
- if arg.dtype == torch.float32:
173
- arg = arg.to(torch.bfloat16).cuda(non_blocking=True)
174
- else:
175
- arg = arg.cuda(non_blocking=True)
176
- new_args.append(arg)
177
-
178
- for k in kwargs:
179
- arg = kwargs[k]
180
- if torch.is_tensor(arg):
181
- if arg.dtype == torch.float32:
182
- arg = arg.to(torch.bfloat16).cuda(non_blocking=True)
183
- else:
184
- arg = arg.cuda(non_blocking=True)
185
- new_kwargs[k]= arg
186
-
187
- return new_args, new_kwargs
188
-
189
- def ready_to_check_mem(self, forceMemoryCheck):
190
- cur_clock = time.time()
191
- # can't check at each call if we can empty the cuda cache as quering the reserved memory value is a time consuming operation
192
- if not forceMemoryCheck and (cur_clock - self.last_reserved_mem_check)<0.200:
193
- return False
194
- self.last_reserved_mem_check = cur_clock
195
- return True
196
-
197
-
198
- def empty_cache_if_needed(self):
199
- mem_reserved = torch.cuda.memory_reserved()
200
- if mem_reserved >= 0.9*self.device_mem_capacity:
201
- mem_allocated = torch.cuda.memory_allocated()
202
- if mem_allocated <= 0.70 * mem_reserved:
203
- # print(f"Cuda empty cache triggered as Allocated Memory ({mem_allocated/1024000:0f} MB) is lot less than Cached Memory ({mem_reserved/1024000:0f} MB) ")
204
- torch.cuda.empty_cache()
205
- # print(f"New cached memory after purge is {torch.cuda.memory_reserved()/1024000:0f} MB) ")
206
-
207
- def hook_me_light(self, target_module, forceMemoryCheck, previous_method):
208
- def check_empty_cache(module, *args, **kwargs):
209
- if self.ready_to_check_mem(forceMemoryCheck):
210
- self.empty_cache_if_needed()
211
- return previous_method(*args, **kwargs)
212
-
213
- setattr(target_module, "forward", functools.update_wrapper(functools.partial(check_empty_cache, target_module), previous_method) )
214
-
215
-
216
- def hook_me(self, target_module, model, model_id, module_id, previous_method):
217
- def check_change_module(module, *args, **kwargs):
218
- performEmptyCacheTest = False
219
- if not model_id in self.active_models_ids:
220
- new_model_id = getattr(module, "_mm_id")
221
- # do not always unload existing models if it is more efficient to keep in them in the GPU
222
- # (e.g: small modules whose calls are text encoders)
223
- if not self.can_model_be_cotenant(new_model_id) :
224
- self.unload_all()
225
- performEmptyCacheTest = False
226
- self.gpu_load(new_model_id)
227
- # transfer leftovers inputs that were incorrectly created in the RAM (mostly due to some .device tests that returned incorrectly "cpu")
228
- args, kwargs = self.move_args_to_gpu(*args, **kwargs)
229
- if performEmptyCacheTest:
230
- self.empty_cache_if_needed()
231
- return previous_method(*args, **kwargs)
232
-
233
- if hasattr(target_module, "_mm_id"):
234
- return
235
- setattr(target_module, "_mm_id", model_id)
236
-
237
- # create a fake accelerate parameter so that the _execution_device property returns always "cuda"
238
- # (it is queried in many pipelines even if offloading is not properly implemented)
239
- if not hasattr(target_module, "_hf_hook"):
240
- setattr(target_module, "_hf_hook", HfHook())
241
- setattr(target_module, "forward", functools.update_wrapper(functools.partial(check_change_module, target_module), previous_method) )
242
-
243
- if not self.verbose:
244
- return
245
-
246
- if module_id == None or module_id =='':
247
- model_name = model._get_name()
248
- print(f"Hooked in model '{model_id}' ({model_name})")
249
-
250
-
251
- # Not implemented yet, but why would one want to get rid of these features ?
252
- # def unhook_module(module: torch.nn.Module):
253
- # if not hasattr(module,"_mm_id"):
254
- # return
255
-
256
- # delattr(module, "_mm_id")
257
-
258
- # def unhook_all(parent_module: torch.nn.Module):
259
- # for module in parent_module.components.items():
260
- # self.unhook_module(module)
261
-
262
-
263
-
264
-
265
- @classmethod
266
- def all(cls, pipe_or_dict_of_modules, quantizeTransformer = True, pinInRAM = False, verbose = True):
267
- self = cls()
268
- self.verbose = verbose
269
- self.pinned_modules_data = {}
270
-
271
- # compile not working yet or slower
272
- compile = False
273
- self.pinInRAM = pinInRAM
274
- pipe = None
275
- preloadInRAM = True
276
- torch.set_default_device('cuda')
277
- if hasattr(pipe_or_dict_of_modules, "components"):
278
- pipe_or_dict_of_modules.to("cpu") #XXXX
279
- # create a fake Accelerate parameter so that lora loading doesn't change the device
280
- pipe_or_dict_of_modules.hf_device_map = torch.device("cuda")
281
- pipe = pipe_or_dict_of_modules
282
- pipe_or_dict_of_modules= pipe_or_dict_of_modules.components
283
-
284
-
285
- models = {k: v for k, v in pipe_or_dict_of_modules.items() if isinstance(v, torch.nn.Module)}
286
-
287
- if quantizeTransformer:
288
- self.models_to_quantize = ["transformer"]
289
- # del models["transformer"] # to test everything but the transformer that has a much longer loading
290
- # models = { 'transformer': pipe_or_dict_of_modules["transformer"]} # to test only the transformer
291
- for model_id in models:
292
- current_model: torch.nn.Module = models[model_id]
293
- # make sure that no RAM or GPU memory is not allocated for gradiant / training
294
- current_model.to("cpu").eval() #XXXXX
295
-
296
- # Quantize model just before transferring it to the RAM to keep OS cache file
297
- # open as short as possible. Indeed it seems that as long as the lazy safetensors
298
- # are not fully fully loaded, the OS won't be able to release the corresponding cache file in RAM.
299
- if model_id in self.models_to_quantize:
300
- print(f"Quantization of model '{model_id}' started")
301
- quantize(current_model, weights=qint8)
302
- freeze(current_model)
303
- print(f"Quantization of model '{model_id}' done")
304
- torch.cuda.empty_cache()
305
- gc.collect()
306
-
307
-
308
-
309
- if preloadInRAM: #
310
- # load all the remaining unread lazy safetensors in RAM to free open cache files
311
- for p in current_model.parameters():
312
- # Preread every tensor in RAM except tensors that have just been quantified
313
- # and are no longer needed
314
- if isinstance(p, QTensor):
315
- # fix quanto bug (see below) now as he won't have any opportunity to do it during RAM pinning
316
- if not pinInRAM and p._scale.dtype == torch.float32:
317
- p._scale = p._scale.to(torch.bfloat16)
318
-
319
- else:
320
- if p.data.dtype == torch.float32:
321
- # convert any left overs float32 weight to bloat16 to divide by 2 the model memory footprint
322
- p.data = p.data.to(torch.bfloat16)
323
- else:
324
- # force reading the tensors from the disk by pretending to modify them
325
- p.data = p.data + 0
326
-
327
-
328
- addModelFlag = False
329
-
330
- current_block_sequence = None
331
- for submodule_name, submodule in current_model.named_modules():
332
- if hasattr(submodule, "forward"):
333
- submodule_method = getattr(submodule, "forward")
334
- if callable(submodule_method):
335
- addModelFlag = True
336
- if submodule_name=='' or len(submodule_name.split("."))==1:
337
- # hook only the first two levels of modules with the full suite of processing
338
- self.hook_me(submodule, current_model, model_id, submodule_name, submodule_method)
339
- else:
340
- forceMemoryCheck = False
341
- pos = submodule_name.find(".0.")
342
- if pos > 0:
343
- if current_block_sequence == None:
344
- new_candidate = submodule_name[0:pos+3]
345
- if len(new_candidate.split("."))<=4:
346
- current_block_sequence = new_candidate
347
- # force a memory check when initiating a new sequence of blocks as the shapes of tensor will certainly change
348
- # and memory reusability is less likely
349
- # we limit this check to the first level of blocks as quering the cuda cache is time consuming
350
- forceMemoryCheck = True
351
- else:
352
- if current_block_sequence != submodule_name[0:len(current_block_sequence)]:
353
- current_block_sequence = None
354
- self.hook_me_light(submodule, forceMemoryCheck, submodule_method)
355
-
356
-
357
- if addModelFlag:
358
- if model_id not in self.models:
359
- self.models[model_id] = current_model
360
-
361
- # Pin in RAM models only once they have been fully loaded otherwise there may be some contention in the non pageable memory
362
- # between partially loaded lazy safetensors and pinned tensors
363
- if pinInRAM:
364
- if verbose:
365
- print("Pinning model tensors in RAM")
366
- torch.cuda.empty_cache()
367
- gc.collect()
368
- for model_id in models:
369
- pinned_parameters_data = {}
370
- current_model: torch.nn.Module = models[model_id]
371
- for p in current_model.parameters():
372
- if isinstance(p, QTensor):
373
- # pin in memory both quantized data and scales of quantized parameters
374
- # but don't pin .data as it corresponds to the original tensor that we don't want to reload
375
- p._data = p._data.pin_memory()
376
- # fix quanto bug that allows _scale to be float32 if the original weight was float32
377
- # (this may cause type mismatch between dequantified bfloat16 weights and float32 scales)
378
- p._scale = p._scale.to(torch.bfloat16).pin_memory() if p._scale.dtype == torch.float32 else p._scale.pin_memory()
379
- pinned_parameters_data[p]=[p._data, p._scale]
380
- else:
381
- p.data = p.data.pin_memory()
382
- pinned_parameters_data[p]=p.data
383
- for b in current_model.buffers():
384
- b.data = b.data.pin_memory()
385
-
386
- pinned_buffers_data = {b: b.data for b in current_model.buffers()}
387
- pinned_parameters_data.update(pinned_buffers_data)
388
- self.pinned_modules_data[model_id]=pinned_parameters_data
389
-
390
- module_params = []
391
- self.params_of_modules[model_id] = module_params
392
- self.collect_module_parameters(current_model,module_params)
393
-
394
- if compile:
395
- if verbose:
396
- print("Torch compilation started")
397
- torch._dynamo.config.cache_size_limit = 10000
398
- # if pipe != None and hasattr(pipe, "__call__"):
399
- # pipe.__call__= torch.compile(pipe.__call__, mode= "max-autotune")
400
-
401
- for model_id in models:
402
- current_model: torch.nn.Module = models[model_id]
403
- current_model.compile(mode= "max-autotune")
404
- #models["transformer"].compile()
405
-
406
- if verbose:
407
- print("Torch compilation done")
408
-
409
- torch.cuda.empty_cache()
410
- gc.collect()
411
-
412
-
413
- return self
414
-
415
-
File without changes
File without changes