mmgp 1.0.6__tar.gz → 1.1.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mmgp
3
- Version: 1.0.6
3
+ Version: 1.1.0
4
4
  Summary: Memory Management for the GPU Poor
5
5
  Author-email: deepbeepmeep <deepbeepmeep@yahoo.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mmgp"
3
- version = "1.0.6"
3
+ version = "1.1.0"
4
4
  authors = [
5
5
  { name = "deepbeepmeep", email = "deepbeepmeep@yahoo.com" },
6
6
  ]
@@ -13,7 +13,3 @@ dependencies = [
13
13
  "optimum-quanto",
14
14
  ]
15
15
 
16
- [tool.setuptools.packages.find]
17
- # All the following settings are optional:
18
- where = ["src"]
19
- namespaces = false
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mmgp
3
- Version: 1.0.6
3
+ Version: 1.1.0
4
4
  Summary: Memory Management for the GPU Poor
5
5
  Author-email: deepbeepmeep <deepbeepmeep@yahoo.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -1,6 +1,8 @@
1
1
  LICENSE.md
2
2
  README.md
3
3
  pyproject.toml
4
+ src/__init__.py
5
+ src/mmgp.py
4
6
  src/mmgp.egg-info/PKG-INFO
5
7
  src/mmgp.egg-info/SOURCES.txt
6
8
  src/mmgp.egg-info/dependency_links.txt
@@ -0,0 +1,2 @@
1
+ __init__
2
+ mmgp
mmgp-1.1.0/src/mmgp.py ADDED
@@ -0,0 +1,415 @@
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
+
@@ -1 +0,0 @@
1
-
File without changes
File without changes
File without changes