mmgp 1.0.6__py3-none-any.whl → 1.2.0__py3-none-any.whl
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.
- __init__.py +0 -0
- mmgp-1.2.0.dist-info/LICENSE.md +2 -0
- mmgp-1.2.0.dist-info/METADATA +109 -0
- mmgp-1.2.0.dist-info/RECORD +7 -0
- mmgp-1.2.0.dist-info/top_level.txt +2 -0
- mmgp.py +421 -0
- mmgp-1.0.6.dist-info/LICENSE.md +0 -674
- mmgp-1.0.6.dist-info/METADATA +0 -755
- mmgp-1.0.6.dist-info/RECORD +0 -5
- mmgp-1.0.6.dist-info/top_level.txt +0 -1
- {mmgp-1.0.6.dist-info → mmgp-1.2.0.dist-info}/WHEEL +0 -0
__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: mmgp
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Memory Management for the GPU Poor
|
|
5
|
+
Author-email: deepbeepmeep <deepbeepmeep@yahoo.com>
|
|
6
|
+
License: GNU GENERAL PUBLIC LICENSE
|
|
7
|
+
Version 3, 29 June 2007
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE.md
|
|
11
|
+
Requires-Dist: torch>=2.1.0
|
|
12
|
+
Requires-Dist: optimum-quanto
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
<p align="center">
|
|
16
|
+
<H2>Memory Management for the GPU Poor by DeepBeepMeep</H2>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
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
|
|
22
|
+
times in a pipe (eg VAE).
|
|
23
|
+
|
|
24
|
+
Requirements:
|
|
25
|
+
- GPU: RTX 3090/ RTX 4090 (24 GB of VRAM)
|
|
26
|
+
- RAM: minimum 48 GB, recommended 64 GB
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
First you need to install the module in your current project with:
|
|
30
|
+
```shell
|
|
31
|
+
pip install mmgp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
It is almost plug and play and just needs to be invoked from the main app just after the model pipeline has been created.
|
|
35
|
+
1) First make sure that the pipeline explictly loads the models in the CPU device, for instance:
|
|
36
|
+
```
|
|
37
|
+
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to("cpu")
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
2) Once every potential Lora has been loaded and merged, add the following lines:
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
from mmgp import offload
|
|
44
|
+
offload.all(pipe)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Options
|
|
48
|
+
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.
|
|
49
|
+
|
|
50
|
+
You can specify a list of additional models string ids to quantize (for instance the text_encoder) using the optional argument *modelsToQuantize* for instance *modelsToQuantize = ["text_encoder_2"]*.This may be useful if you have less than 48 GB of RAM.
|
|
51
|
+
|
|
52
|
+
Note that there is little advantage on the GPU / VRAM side to quantize text encoders as their inputs are usually quite light.
|
|
53
|
+
|
|
54
|
+
Conversely if you have more than 64GB of RAM you may want to enable RAM pinning with the option *pinInRAM = True*. You will get in return super fast loading / unloading of models
|
|
55
|
+
(this can save significant time if the same pipeline is run multiple times in a row)
|
|
56
|
+
|
|
57
|
+
In Summary, if you have:
|
|
58
|
+
- Between 32 GB and 48 GB of RAM
|
|
59
|
+
```
|
|
60
|
+
offload.all(pipe, modelsToQuantize = ["text_encoder_2"]) # for Flux models
|
|
61
|
+
#OR
|
|
62
|
+
offload.all(pipe, modelsToQuantize = ["text_encoder"]) # for HunyuanVideo models
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- Between 48 GB and 64 GB of RAM
|
|
67
|
+
```
|
|
68
|
+
offload.all(pipe)
|
|
69
|
+
```
|
|
70
|
+
- More than 64 GB of RAM
|
|
71
|
+
```
|
|
72
|
+
offload.all(pipe), pinInRAM = True
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Special
|
|
76
|
+
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.\
|
|
77
|
+
For instance :
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
- for flux derived models:
|
|
81
|
+
```
|
|
82
|
+
pipe = { "text_encoder": clip, "text_encoder_2": t5, "transformer": model, "vae":ae }
|
|
83
|
+
```
|
|
84
|
+
- for mochi:
|
|
85
|
+
```
|
|
86
|
+
pipe = { "text_encoder": self.text_encoder, "transformer": self.dit, "vae":self.decoder }
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
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).
|
|
91
|
+
|
|
92
|
+
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
|
|
93
|
+
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.
|
|
94
|
+
I suggest you use instead one of the 16 bits encoder only version available around, for instance:
|
|
95
|
+
```
|
|
96
|
+
text_encoder_2 = T5EncoderModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", torch_dtype=torch.float16)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
|
|
100
|
+
- 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)
|
|
101
|
+
- 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.
|
|
102
|
+
|
|
103
|
+
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
|
|
104
|
+
|
|
105
|
+
Thanks to
|
|
106
|
+
---------
|
|
107
|
+
- Huggingface / accelerate for the hooking examples
|
|
108
|
+
- Huggingface / quanto for their very useful quantizer
|
|
109
|
+
- gau-nernst for his Pinnig RAM samples
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
mmgp.py,sha256=IijgE22bUPl98VvXwoC1qngmkdWU11YXjkiksp8o1hY,21418
|
|
3
|
+
mmgp-1.2.0.dist-info/LICENSE.md,sha256=HjzvY2grdtdduZclbZ46B2M-XpT4MDCxFub5ZwTWq2g,93
|
|
4
|
+
mmgp-1.2.0.dist-info/METADATA,sha256=jRXi-iNZ_3zNNVxMC1qmVDd7ylq8kAr5Y5FgYyBvVh4,4897
|
|
5
|
+
mmgp-1.2.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
|
6
|
+
mmgp-1.2.0.dist-info/top_level.txt,sha256=waGaepj2qVfnS2yAOkaMu4r9mJaVjGbEi6AwOUogU_U,14
|
|
7
|
+
mmgp-1.2.0.dist-info/RECORD,,
|
mmgp.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
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.all(pipe)
|
|
17
|
+
# The 'transformer' model that contains usually the video or image generator is quantized on the fly by default to 8 bits so that it can fit into 24 GB of VRAM.
|
|
18
|
+
# 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.
|
|
19
|
+
# You can specify a list of additional models string ids to quantize (for instance the text_encoder) using the optional argument modelsToQuantize. This may be useful if you have less than 48 GB of RAM.
|
|
20
|
+
# Note that there is little advantage on the GPU / VRAM side to quantize text encoders as their inputs are usually quite light.
|
|
21
|
+
# Conversely 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
|
+
# (this can save significant time if the same pipeline is run multiple times in a row)
|
|
23
|
+
#
|
|
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
|
+
#
|
|
26
|
+
# 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 }
|
|
29
|
+
#
|
|
30
|
+
# 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
|
+
#
|
|
32
|
+
# 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
|
+
# 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
|
+
# 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)
|
|
36
|
+
#
|
|
37
|
+
# Sometime just providing the pipe won't be sufficient as you will need to change the content of the core model:
|
|
38
|
+
# - 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)
|
|
39
|
+
# - 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.
|
|
40
|
+
#
|
|
41
|
+
# 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
|
|
42
|
+
#
|
|
43
|
+
# Thanks to
|
|
44
|
+
# ---------
|
|
45
|
+
# Huggingface / accelerate for the hooking examples
|
|
46
|
+
# Huggingface / quanto for their very useful quantizer
|
|
47
|
+
# gau-nernst for his Pinnig RAM samples
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
#
|
|
51
|
+
import torch
|
|
52
|
+
#
|
|
53
|
+
import gc
|
|
54
|
+
import time
|
|
55
|
+
import functools
|
|
56
|
+
from optimum.quanto import freeze, qfloat8, qint8, quantize, QModuleMixin, QTensor
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
cotenants_map = {
|
|
61
|
+
"text_encoder": ["vae", "text_encoder_2"],
|
|
62
|
+
"text_encoder_2": ["vae", "text_encoder"],
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# useful functions to move a group of tensors (to design custom offload patches)
|
|
66
|
+
def move_tensors(obj, device):
|
|
67
|
+
if torch.is_tensor(obj):
|
|
68
|
+
return obj.to(device)
|
|
69
|
+
elif isinstance(obj, dict):
|
|
70
|
+
_dict = {}
|
|
71
|
+
for k, v in obj.items():
|
|
72
|
+
_dict[k] = move_tensors(v, device)
|
|
73
|
+
return _dict
|
|
74
|
+
elif isinstance(obj, list):
|
|
75
|
+
_list = []
|
|
76
|
+
for v in obj:
|
|
77
|
+
_list.append(move_tensors(v, device))
|
|
78
|
+
return _list
|
|
79
|
+
else:
|
|
80
|
+
raise TypeError("Tensor or list / dict of tensors expected")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_model_name(model):
|
|
84
|
+
return model.name
|
|
85
|
+
|
|
86
|
+
class HfHook:
|
|
87
|
+
def __init__(self):
|
|
88
|
+
self.execution_device = "cuda"
|
|
89
|
+
|
|
90
|
+
def detach_hook(self, module):
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
class offload:
|
|
94
|
+
def __init__(self):
|
|
95
|
+
self.active_models = []
|
|
96
|
+
self.active_models_ids = []
|
|
97
|
+
self.models = {}
|
|
98
|
+
self.verbose = False
|
|
99
|
+
self.models_to_quantize = []
|
|
100
|
+
self.pinned_modules_data = {}
|
|
101
|
+
self.params_of_modules = {}
|
|
102
|
+
self.pinTensors = False
|
|
103
|
+
self.device_mem_capacity = torch.cuda.get_device_properties(0).total_memory
|
|
104
|
+
self.last_reserved_mem_check =0
|
|
105
|
+
|
|
106
|
+
def collect_module_parameters(self, module: torch.nn.Module, module_params):
|
|
107
|
+
if isinstance(module, (torch.nn.ModuleList, torch.nn.Sequential)):
|
|
108
|
+
for i in range(len(module)):
|
|
109
|
+
current_layer = module[i]
|
|
110
|
+
module_params.extend(current_layer.parameters())
|
|
111
|
+
module_params.extend(current_layer.buffers())
|
|
112
|
+
else:
|
|
113
|
+
for p in module.parameters(recurse=False):
|
|
114
|
+
module_params.append(p)
|
|
115
|
+
for p in module.buffers(recurse=False):
|
|
116
|
+
module_params.append(p)
|
|
117
|
+
for sub_module in module.children():
|
|
118
|
+
self.collect_module_parameters(sub_module, module_params)
|
|
119
|
+
|
|
120
|
+
def can_model_be_cotenant(self, model_id):
|
|
121
|
+
potential_cotenants= cotenants_map.get(model_id, None)
|
|
122
|
+
if potential_cotenants is None:
|
|
123
|
+
return False
|
|
124
|
+
for existing_cotenant in self.active_models_ids:
|
|
125
|
+
if existing_cotenant not in potential_cotenants:
|
|
126
|
+
return False
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
def gpu_load(self, model_id):
|
|
130
|
+
model = self.models[model_id]
|
|
131
|
+
self.active_models.append(model)
|
|
132
|
+
self.active_models_ids.append(model_id)
|
|
133
|
+
if self.verbose:
|
|
134
|
+
model_name = model._get_name()
|
|
135
|
+
print(f"Loading model {model_name} ({model_id}) in GPU")
|
|
136
|
+
if not self.pinInRAM:
|
|
137
|
+
model.to("cuda")
|
|
138
|
+
else:
|
|
139
|
+
module_params = self.params_of_modules[model_id]
|
|
140
|
+
for p in module_params:
|
|
141
|
+
if isinstance(p, QTensor):
|
|
142
|
+
p._data = p._data.cuda(non_blocking=True)
|
|
143
|
+
p._scale = p._scale.cuda(non_blocking=True)
|
|
144
|
+
else:
|
|
145
|
+
p.data = p.data.cuda(non_blocking=True) #
|
|
146
|
+
# torch.cuda.current_stream().synchronize()
|
|
147
|
+
@torch.compiler.disable()
|
|
148
|
+
def unload_all(self):
|
|
149
|
+
for model, model_id in zip(self.active_models, self.active_models_ids):
|
|
150
|
+
if not self.pinInRAM:
|
|
151
|
+
model.to("cpu")
|
|
152
|
+
else:
|
|
153
|
+
module_params = self.params_of_modules[model_id]
|
|
154
|
+
pinned_parameters_data = self.pinned_modules_data[model_id]
|
|
155
|
+
for p in module_params:
|
|
156
|
+
if isinstance(p, QTensor):
|
|
157
|
+
data = pinned_parameters_data[p]
|
|
158
|
+
p._data = data[0]
|
|
159
|
+
p._scale = data[1]
|
|
160
|
+
else:
|
|
161
|
+
p.data = pinned_parameters_data[p]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
self.active_models = []
|
|
165
|
+
self.active_models_ids = []
|
|
166
|
+
torch.cuda.empty_cache()
|
|
167
|
+
gc.collect()
|
|
168
|
+
|
|
169
|
+
def move_args_to_gpu(self, *args, **kwargs):
|
|
170
|
+
new_args= []
|
|
171
|
+
new_kwargs={}
|
|
172
|
+
for arg in args:
|
|
173
|
+
if torch.is_tensor(arg):
|
|
174
|
+
if arg.dtype == torch.float32:
|
|
175
|
+
arg = arg.to(torch.bfloat16).cuda(non_blocking=True)
|
|
176
|
+
else:
|
|
177
|
+
arg = arg.cuda(non_blocking=True)
|
|
178
|
+
new_args.append(arg)
|
|
179
|
+
|
|
180
|
+
for k in kwargs:
|
|
181
|
+
arg = kwargs[k]
|
|
182
|
+
if torch.is_tensor(arg):
|
|
183
|
+
if arg.dtype == torch.float32:
|
|
184
|
+
arg = arg.to(torch.bfloat16).cuda(non_blocking=True)
|
|
185
|
+
else:
|
|
186
|
+
arg = arg.cuda(non_blocking=True)
|
|
187
|
+
new_kwargs[k]= arg
|
|
188
|
+
|
|
189
|
+
return new_args, new_kwargs
|
|
190
|
+
|
|
191
|
+
def ready_to_check_mem(self, forceMemoryCheck):
|
|
192
|
+
cur_clock = time.time()
|
|
193
|
+
# can't check at each call if we can empty the cuda cache as quering the reserved memory value is a time consuming operation
|
|
194
|
+
if not forceMemoryCheck and (cur_clock - self.last_reserved_mem_check)<0.200:
|
|
195
|
+
return False
|
|
196
|
+
self.last_reserved_mem_check = cur_clock
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def empty_cache_if_needed(self):
|
|
201
|
+
mem_reserved = torch.cuda.memory_reserved()
|
|
202
|
+
if mem_reserved >= 0.9*self.device_mem_capacity:
|
|
203
|
+
mem_allocated = torch.cuda.memory_allocated()
|
|
204
|
+
if mem_allocated <= 0.70 * mem_reserved:
|
|
205
|
+
# 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) ")
|
|
206
|
+
torch.cuda.empty_cache()
|
|
207
|
+
# print(f"New cached memory after purge is {torch.cuda.memory_reserved()/1024000:0f} MB) ")
|
|
208
|
+
|
|
209
|
+
def hook_me_light(self, target_module, forceMemoryCheck, previous_method):
|
|
210
|
+
def check_empty_cache(module, *args, **kwargs):
|
|
211
|
+
if self.ready_to_check_mem(forceMemoryCheck):
|
|
212
|
+
self.empty_cache_if_needed()
|
|
213
|
+
return previous_method(*args, **kwargs)
|
|
214
|
+
|
|
215
|
+
setattr(target_module, "forward", functools.update_wrapper(functools.partial(check_empty_cache, target_module), previous_method) )
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def hook_me(self, target_module, model, model_id, module_id, previous_method):
|
|
219
|
+
def check_change_module(module, *args, **kwargs):
|
|
220
|
+
performEmptyCacheTest = False
|
|
221
|
+
if not model_id in self.active_models_ids:
|
|
222
|
+
new_model_id = getattr(module, "_mm_id")
|
|
223
|
+
# do not always unload existing models if it is more efficient to keep in them in the GPU
|
|
224
|
+
# (e.g: small modules whose calls are text encoders)
|
|
225
|
+
if not self.can_model_be_cotenant(new_model_id) :
|
|
226
|
+
self.unload_all()
|
|
227
|
+
performEmptyCacheTest = False
|
|
228
|
+
self.gpu_load(new_model_id)
|
|
229
|
+
# transfer leftovers inputs that were incorrectly created in the RAM (mostly due to some .device tests that returned incorrectly "cpu")
|
|
230
|
+
args, kwargs = self.move_args_to_gpu(*args, **kwargs)
|
|
231
|
+
if performEmptyCacheTest:
|
|
232
|
+
self.empty_cache_if_needed()
|
|
233
|
+
return previous_method(*args, **kwargs)
|
|
234
|
+
|
|
235
|
+
if hasattr(target_module, "_mm_id"):
|
|
236
|
+
return
|
|
237
|
+
setattr(target_module, "_mm_id", model_id)
|
|
238
|
+
|
|
239
|
+
# create a fake accelerate parameter so that the _execution_device property returns always "cuda"
|
|
240
|
+
# (it is queried in many pipelines even if offloading is not properly implemented)
|
|
241
|
+
if not hasattr(target_module, "_hf_hook"):
|
|
242
|
+
setattr(target_module, "_hf_hook", HfHook())
|
|
243
|
+
setattr(target_module, "forward", functools.update_wrapper(functools.partial(check_change_module, target_module), previous_method) )
|
|
244
|
+
|
|
245
|
+
if not self.verbose:
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
if module_id == None or module_id =='':
|
|
249
|
+
model_name = model._get_name()
|
|
250
|
+
print(f"Hooked in model '{model_id}' ({model_name})")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# Not implemented yet, but why would one want to get rid of these features ?
|
|
254
|
+
# def unhook_module(module: torch.nn.Module):
|
|
255
|
+
# if not hasattr(module,"_mm_id"):
|
|
256
|
+
# return
|
|
257
|
+
|
|
258
|
+
# delattr(module, "_mm_id")
|
|
259
|
+
|
|
260
|
+
# def unhook_all(parent_module: torch.nn.Module):
|
|
261
|
+
# for module in parent_module.components.items():
|
|
262
|
+
# self.unhook_module(module)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@classmethod
|
|
268
|
+
def all(cls, pipe_or_dict_of_modules, quantizeTransformer = True, pinInRAM = False, verbose = True, modelsToQuantize = None ):
|
|
269
|
+
self = cls()
|
|
270
|
+
self.verbose = verbose
|
|
271
|
+
self.pinned_modules_data = {}
|
|
272
|
+
|
|
273
|
+
# compile not working yet or slower
|
|
274
|
+
compile = False
|
|
275
|
+
self.pinInRAM = pinInRAM
|
|
276
|
+
pipe = None
|
|
277
|
+
preloadInRAM = True
|
|
278
|
+
torch.set_default_device('cuda')
|
|
279
|
+
if hasattr(pipe_or_dict_of_modules, "components"):
|
|
280
|
+
pipe_or_dict_of_modules.to("cpu") #XXXX
|
|
281
|
+
# create a fake Accelerate parameter so that lora loading doesn't change the device
|
|
282
|
+
pipe_or_dict_of_modules.hf_device_map = torch.device("cuda")
|
|
283
|
+
pipe = pipe_or_dict_of_modules
|
|
284
|
+
pipe_or_dict_of_modules= pipe_or_dict_of_modules.components
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
models = {k: v for k, v in pipe_or_dict_of_modules.items() if isinstance(v, torch.nn.Module)}
|
|
288
|
+
|
|
289
|
+
modelsToQuantize = modelsToQuantize if modelsToQuantize is not None else []
|
|
290
|
+
if not isinstance(modelsToQuantize, list):
|
|
291
|
+
modelsToQuantize = [modelsToQuantize]
|
|
292
|
+
if quantizeTransformer:
|
|
293
|
+
modelsToQuantize.append("transformer")
|
|
294
|
+
self.models_to_quantize = modelsToQuantize
|
|
295
|
+
# del models["transformer"] # to test everything but the transformer that has a much longer loading
|
|
296
|
+
# models = { 'transformer': pipe_or_dict_of_modules["transformer"]} # to test only the transformer
|
|
297
|
+
for model_id in models:
|
|
298
|
+
current_model: torch.nn.Module = models[model_id]
|
|
299
|
+
# make sure that no RAM or GPU memory is not allocated for gradiant / training
|
|
300
|
+
current_model.to("cpu").eval() #XXXXX
|
|
301
|
+
|
|
302
|
+
# Quantize model just before transferring it to the RAM to keep OS cache file
|
|
303
|
+
# open as short as possible. Indeed it seems that as long as the lazy safetensors
|
|
304
|
+
# are not fully fully loaded, the OS won't be able to release the corresponding cache file in RAM.
|
|
305
|
+
if model_id in self.models_to_quantize:
|
|
306
|
+
print(f"Quantization of model '{model_id}' started")
|
|
307
|
+
quantize(current_model, weights=qint8)
|
|
308
|
+
freeze(current_model)
|
|
309
|
+
print(f"Quantization of model '{model_id}' done")
|
|
310
|
+
torch.cuda.empty_cache()
|
|
311
|
+
gc.collect()
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
if preloadInRAM: #
|
|
316
|
+
# load all the remaining unread lazy safetensors in RAM to free open cache files
|
|
317
|
+
for p in current_model.parameters():
|
|
318
|
+
# Preread every tensor in RAM except tensors that have just been quantified
|
|
319
|
+
# and are no longer needed
|
|
320
|
+
if isinstance(p, QTensor):
|
|
321
|
+
# fix quanto bug (see below) now as he won't have any opportunity to do it during RAM pinning
|
|
322
|
+
if not pinInRAM and p._scale.dtype == torch.float32:
|
|
323
|
+
p._scale = p._scale.to(torch.bfloat16)
|
|
324
|
+
|
|
325
|
+
else:
|
|
326
|
+
if p.data.dtype == torch.float32:
|
|
327
|
+
# convert any left overs float32 weight to bloat16 to divide by 2 the model memory footprint
|
|
328
|
+
p.data = p.data.to(torch.bfloat16)
|
|
329
|
+
else:
|
|
330
|
+
# force reading the tensors from the disk by pretending to modify them
|
|
331
|
+
p.data = p.data + 0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
addModelFlag = False
|
|
335
|
+
|
|
336
|
+
current_block_sequence = None
|
|
337
|
+
for submodule_name, submodule in current_model.named_modules():
|
|
338
|
+
if hasattr(submodule, "forward"):
|
|
339
|
+
submodule_method = getattr(submodule, "forward")
|
|
340
|
+
if callable(submodule_method):
|
|
341
|
+
addModelFlag = True
|
|
342
|
+
if submodule_name=='' or len(submodule_name.split("."))==1:
|
|
343
|
+
# hook only the first two levels of modules with the full suite of processing
|
|
344
|
+
self.hook_me(submodule, current_model, model_id, submodule_name, submodule_method)
|
|
345
|
+
else:
|
|
346
|
+
forceMemoryCheck = False
|
|
347
|
+
pos = submodule_name.find(".0.")
|
|
348
|
+
if pos > 0:
|
|
349
|
+
if current_block_sequence == None:
|
|
350
|
+
new_candidate = submodule_name[0:pos+3]
|
|
351
|
+
if len(new_candidate.split("."))<=4:
|
|
352
|
+
current_block_sequence = new_candidate
|
|
353
|
+
# force a memory check when initiating a new sequence of blocks as the shapes of tensor will certainly change
|
|
354
|
+
# and memory reusability is less likely
|
|
355
|
+
# we limit this check to the first level of blocks as quering the cuda cache is time consuming
|
|
356
|
+
forceMemoryCheck = True
|
|
357
|
+
else:
|
|
358
|
+
if current_block_sequence != submodule_name[0:len(current_block_sequence)]:
|
|
359
|
+
current_block_sequence = None
|
|
360
|
+
self.hook_me_light(submodule, forceMemoryCheck, submodule_method)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
if addModelFlag:
|
|
364
|
+
if model_id not in self.models:
|
|
365
|
+
self.models[model_id] = current_model
|
|
366
|
+
|
|
367
|
+
# Pin in RAM models only once they have been fully loaded otherwise there may be some contention in the non pageable memory
|
|
368
|
+
# between partially loaded lazy safetensors and pinned tensors
|
|
369
|
+
if pinInRAM:
|
|
370
|
+
if verbose:
|
|
371
|
+
print("Pinning model tensors in RAM")
|
|
372
|
+
torch.cuda.empty_cache()
|
|
373
|
+
gc.collect()
|
|
374
|
+
for model_id in models:
|
|
375
|
+
pinned_parameters_data = {}
|
|
376
|
+
current_model: torch.nn.Module = models[model_id]
|
|
377
|
+
for p in current_model.parameters():
|
|
378
|
+
if isinstance(p, QTensor):
|
|
379
|
+
# pin in memory both quantized data and scales of quantized parameters
|
|
380
|
+
# but don't pin .data as it corresponds to the original tensor that we don't want to reload
|
|
381
|
+
p._data = p._data.pin_memory()
|
|
382
|
+
# fix quanto bug that allows _scale to be float32 if the original weight was float32
|
|
383
|
+
# (this may cause type mismatch between dequantified bfloat16 weights and float32 scales)
|
|
384
|
+
p._scale = p._scale.to(torch.bfloat16).pin_memory() if p._scale.dtype == torch.float32 else p._scale.pin_memory()
|
|
385
|
+
pinned_parameters_data[p]=[p._data, p._scale]
|
|
386
|
+
else:
|
|
387
|
+
p.data = p.data.pin_memory()
|
|
388
|
+
pinned_parameters_data[p]=p.data
|
|
389
|
+
for b in current_model.buffers():
|
|
390
|
+
b.data = b.data.pin_memory()
|
|
391
|
+
|
|
392
|
+
pinned_buffers_data = {b: b.data for b in current_model.buffers()}
|
|
393
|
+
pinned_parameters_data.update(pinned_buffers_data)
|
|
394
|
+
self.pinned_modules_data[model_id]=pinned_parameters_data
|
|
395
|
+
|
|
396
|
+
module_params = []
|
|
397
|
+
self.params_of_modules[model_id] = module_params
|
|
398
|
+
self.collect_module_parameters(current_model,module_params)
|
|
399
|
+
|
|
400
|
+
if compile:
|
|
401
|
+
if verbose:
|
|
402
|
+
print("Torch compilation started")
|
|
403
|
+
torch._dynamo.config.cache_size_limit = 10000
|
|
404
|
+
# if pipe != None and hasattr(pipe, "__call__"):
|
|
405
|
+
# pipe.__call__= torch.compile(pipe.__call__, mode= "max-autotune")
|
|
406
|
+
|
|
407
|
+
for model_id in models:
|
|
408
|
+
current_model: torch.nn.Module = models[model_id]
|
|
409
|
+
current_model.compile(mode= "max-autotune")
|
|
410
|
+
#models["transformer"].compile()
|
|
411
|
+
|
|
412
|
+
if verbose:
|
|
413
|
+
print("Torch compilation done")
|
|
414
|
+
|
|
415
|
+
torch.cuda.empty_cache()
|
|
416
|
+
gc.collect()
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
return self
|
|
420
|
+
|
|
421
|
+
|