2vXpSwA7 commited on
Commit
fcd264e
·
verified ·
1 Parent(s): b097751

Upload sdmodel_unloader.py

Browse files
Files changed (1) hide show
  1. sdmodel_unloader.py +283 -0
sdmodel_unloader.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from modules import scripts, shared, sd_models, lowvram, devices, paths
3
+ import gc
4
+ import torch
5
+ import os
6
+
7
+ try:
8
+ from modules.sd_models import forge_model_reload, model_data, CheckpointInfo
9
+ from modules_forge.main_entry import forge_unet_storage_dtype_options
10
+ from backend.memory_management import free_memory as forge_free_memory
11
+ from modules.timer import Timer
12
+ forge = True
13
+ except ImportError:
14
+ forge = False
15
+ class CheckpointInfo:
16
+ def __init__(self, filename):
17
+ self.filename = filename
18
+ self.name = os.path.splitext(os.path.basename(filename))[0]
19
+ self.name_or_path = filename
20
+ self.sha256 = None
21
+ self.ids = None
22
+ self.model_name = self.name
23
+ self.title = self.name
24
+ class Timer:
25
+ def record(self, *args, **kwargs): pass
26
+
27
+ class ModelUtilState:
28
+ last_loaded_checkpoint_info_dict = None
29
+ last_forge_model_params = None
30
+ is_model_unloaded_by_ext = False
31
+
32
+ state = ModelUtilState()
33
+
34
+ def get_current_checkpoint_info():
35
+ if forge and hasattr(model_data, 'sd_checkpoint_info') and model_data.sd_checkpoint_info:
36
+ return model_data.sd_checkpoint_info
37
+ if hasattr(shared, 'sd_model') and shared.sd_model and hasattr(shared.sd_model, 'sd_checkpoint_info') and shared.sd_model.sd_checkpoint_info:
38
+ return shared.sd_model.sd_checkpoint_info
39
+ if shared.opts.sd_model_checkpoint:
40
+ checkpoint_path = sd_models.get_checkpoint_path(shared.opts.sd_model_checkpoint)
41
+ if checkpoint_path:
42
+ return CheckpointInfo(checkpoint_path)
43
+ return None
44
+
45
+ def checkpoint_info_to_dict(chkpt_info):
46
+ if not chkpt_info:
47
+ return None
48
+ return {
49
+ "filename": getattr(chkpt_info, 'filename', None),
50
+ "name": getattr(chkpt_info, 'name', None),
51
+ "name_or_path": getattr(chkpt_info, 'name_or_path', getattr(chkpt_info, 'filename', None)),
52
+ "sha256": getattr(chkpt_info, 'sha256', None),
53
+ "model_name": getattr(chkpt_info, 'model_name', None),
54
+ "title": getattr(chkpt_info, 'title', None),
55
+ }
56
+
57
+ def ensure_name_or_path(info_obj):
58
+ if not info_obj:
59
+ return info_obj
60
+ if not hasattr(info_obj, 'name_or_path') or not getattr(info_obj, 'name_or_path', None):
61
+ filename_attr = getattr(info_obj, 'filename', None)
62
+ title_attr = getattr(info_obj, 'title', None)
63
+ name_attr = getattr(info_obj, 'name', None)
64
+ if filename_attr:
65
+ print(f"Info object was missing 'name_or_path'. Setting from 'filename': {filename_attr}")
66
+ info_obj.name_or_path = filename_attr
67
+ elif title_attr:
68
+ print(f"Info object was missing 'name_or_path/filename'. Setting from 'title': {title_attr}")
69
+ info_obj.name_or_path = title_attr
70
+ elif name_attr:
71
+ print(f"Info object was missing 'name_or_path/filename/title'. Setting from 'name': {name_attr}")
72
+ info_obj.name_or_path = name_attr
73
+ else:
74
+ print(f"CRITICAL: Info object is missing 'name_or_path', 'filename', 'title', and 'name'. Cannot reliably set 'name_or_path'.")
75
+ return info_obj
76
+
77
+ def dict_to_checkpoint_info(chkpt_dict):
78
+ if not chkpt_dict or not chkpt_dict.get('name_or_path'):
79
+ print(f"Warning: chkpt_dict is invalid or missing 'name_or_path': {chkpt_dict}")
80
+ return None
81
+
82
+ target_model_identifier = chkpt_dict['name_or_path']
83
+ print(f"Attempting to find CheckpointInfo for: {target_model_identifier}")
84
+
85
+ available_checkpoints = sd_models.checkpoints_list
86
+ found_info = None
87
+
88
+ for name, info_obj_from_list in available_checkpoints.items():
89
+ info_name_or_path = getattr(info_obj_from_list, 'name_or_path', None)
90
+ info_filename = getattr(info_obj_from_list, 'filename', None)
91
+ info_title = getattr(info_obj_from_list, 'title', None)
92
+ match_found = False
93
+ if info_name_or_path and info_name_or_path == target_model_identifier: match_found = True
94
+ elif info_filename and info_filename == target_model_identifier: match_found = True
95
+ elif name == target_model_identifier: match_found = True
96
+ elif info_title and info_title == target_model_identifier: match_found = True
97
+ if match_found:
98
+ print(f"Found matching CheckpointInfo in available_checkpoints: {name}")
99
+ found_info = info_obj_from_list
100
+ break
101
+ if found_info:
102
+ return ensure_name_or_path(found_info)
103
+
104
+ print(f"CheckpointInfo for '{target_model_identifier}' not found in list. Attempting to create new one.")
105
+ if os.path.exists(target_model_identifier):
106
+ print(f"File exists at path: {target_model_identifier}. Creating new CheckpointInfo.")
107
+ newly_created_info = CheckpointInfo(target_model_identifier)
108
+ for key, value in chkpt_dict.items():
109
+ if not hasattr(newly_created_info, key) or getattr(newly_created_info, key) is None:
110
+ setattr(newly_created_info, key, value)
111
+ return ensure_name_or_path(newly_created_info)
112
+ else:
113
+ print(f"File does not exist at path: {target_model_identifier}. Cannot create CheckpointInfo.")
114
+
115
+ print(f"Warning: Could not reconstruct CheckpointInfo for {target_model_identifier}.")
116
+ return None
117
+
118
+
119
+ def unload_model_logic():
120
+ model_loaded = (forge and hasattr(model_data, 'sd_model') and model_data.sd_model) or \
121
+ (not forge and hasattr(shared, 'sd_model') and shared.sd_model)
122
+ if not model_loaded:
123
+ state.is_model_unloaded_by_ext = False
124
+ return "Model is already unloaded or not loaded."
125
+
126
+ print("Unloading SD model...")
127
+ current_info = get_current_checkpoint_info()
128
+ if current_info:
129
+ state.last_loaded_checkpoint_info_dict = checkpoint_info_to_dict(current_info)
130
+ print(f"Storing info for model: {state.last_loaded_checkpoint_info_dict.get('name_or_path')}")
131
+ else:
132
+ state.last_loaded_checkpoint_info_dict = None
133
+ print("Could not get current checkpoint info to store.")
134
+
135
+ if forge:
136
+ if hasattr(model_data, "forge_loading_parameters") and model_data.forge_loading_parameters:
137
+ state.last_forge_model_params = model_data.forge_loading_parameters.copy()
138
+ else:
139
+ state.last_forge_model_params = None
140
+ sd_models.model_data.sd_model = None
141
+ if hasattr(sd_models.model_data, 'loaded_sd_models'):
142
+ sd_models.model_data.loaded_sd_models = []
143
+ if hasattr(sd_models.model_data, 'forge_objects'):
144
+ for attr in ['unet', 'vae', 'clip_l', 'clip_g', 'clip_vision', 'gligen', 'controlnet_predict', 'patch_manager', 'conditioner']: # Added conditioner
145
+ if hasattr(sd_models.model_data.forge_objects, attr):
146
+ setattr(sd_models.model_data.forge_objects, attr, None)
147
+ cuda_device_str = devices.get_cuda_device_string() if torch.cuda.is_available() else "cpu"
148
+ if torch.cuda.is_available():
149
+ forge_free_memory(torch.cuda.memory_allocated(cuda_device_str), cuda_device_str, free_all=True)
150
+ print("Forge model components cleared and memory freed.")
151
+ else:
152
+ sd_models.unload_model_weights()
153
+ print("Standard model unloaded.")
154
+
155
+ lowvram.module_in_gpu = None
156
+ shared.sd_model = None
157
+ gc.collect()
158
+ if torch.cuda.is_available():
159
+ torch.cuda.empty_cache()
160
+ state.is_model_unloaded_by_ext = True
161
+ return "Model unloaded successfully. VRAM freed."
162
+
163
+ def _ensure_module_on_device(module, module_name, target_device, indent=" "):
164
+ if module and isinstance(module, torch.nn.Module) and next(module.parameters(), None) is not None:
165
+ current_device = next(module.parameters()).device
166
+ if current_device.type != target_device.type or (target_device.type == 'cuda' and current_device.index != target_device.index):
167
+ print(f"{indent}Moving {module_name} from {current_device} to {target_device}...")
168
+ module.to(target_device)
169
+ return True
170
+ return False
171
+
172
+ def reload_last_model_logic():
173
+ model_currently_loaded = (forge and hasattr(model_data, 'sd_model') and model_data.sd_model and model_data.sd_model is not shared.sd_model_empty) or \
174
+ (not forge and hasattr(shared, 'sd_model') and shared.sd_model and shared.sd_model is not shared.sd_model_empty)
175
+
176
+ if model_currently_loaded and not state.is_model_unloaded_by_ext:
177
+ return "Model is already loaded and was not unloaded by this extension. No action taken."
178
+
179
+ if not state.last_loaded_checkpoint_info_dict:
180
+ if shared.opts.sd_model_checkpoint:
181
+ print(f"No specific model info stored by extension, trying to use WebUI's selected model: {shared.opts.sd_model_checkpoint}")
182
+ checkpoint_path = sd_models.get_checkpoint_path(shared.opts.sd_model_checkpoint)
183
+ if checkpoint_path:
184
+ state.last_loaded_checkpoint_info_dict = checkpoint_info_to_dict(CheckpointInfo(checkpoint_path))
185
+ else:
186
+ return "No last model information found and WebUI's selected model could not be resolved."
187
+ else:
188
+ return "No last model information found to reload."
189
+
190
+ chkpt_info_to_load = dict_to_checkpoint_info(state.last_loaded_checkpoint_info_dict)
191
+ if not chkpt_info_to_load or not getattr(chkpt_info_to_load, 'name_or_path', None):
192
+ return f"Could not reconstruct valid CheckpointInfo from stored data: {state.last_loaded_checkpoint_info_dict}. Cannot reload."
193
+
194
+ model_display_name = getattr(chkpt_info_to_load, 'name_or_path', getattr(chkpt_info_to_load, 'filename', 'Unknown Model'))
195
+ print(f"Reloading SD model: {model_display_name}")
196
+
197
+ try:
198
+ devices.torch_gc()
199
+
200
+ if forge:
201
+ print("Forge: Reloading using forge_model_reload()...")
202
+ if state.last_forge_model_params:
203
+ sd_models.model_data.forge_loading_parameters = state.last_forge_model_params.copy()
204
+ sd_models.model_data.forge_loading_parameters['checkpoint_info'] = chkpt_info_to_load
205
+ else:
206
+ print("Warning: No specific Forge params stored, building defaults for reload.")
207
+ unet_storage_dtype, _ = forge_unet_storage_dtype_options.get(shared.opts.forge_unet_storage_dtype, (None, False))
208
+ sd_models.model_data.forge_loading_parameters = dict(
209
+ checkpoint_info=chkpt_info_to_load,
210
+ additional_modules=shared.opts.forge_additional_modules,
211
+ unet_storage_dtype=unet_storage_dtype
212
+ )
213
+ sd_models.model_data.forge_hash = None
214
+
215
+ forge_model_reload()
216
+
217
+ if not sd_models.model_data.sd_model:
218
+ raise RuntimeError("forge_model_reload() did not populate model_data.sd_model.")
219
+
220
+ shared.sd_model = sd_models.model_data.sd_model
221
+ print("Forge: forge_model_reload() completed.")
222
+
223
+ if torch.cuda.is_available():
224
+ cuda_device = torch.device(devices.get_cuda_device_string())
225
+ print(f"Forge: Verifying device placement on {cuda_device} after reload...")
226
+
227
+ _ensure_module_on_device(shared.sd_model, "shared.sd_model (main)", cuda_device)
228
+
229
+ if hasattr(shared.sd_model, 'forge_objects') and shared.sd_model.forge_objects:
230
+ fo = shared.sd_model.forge_objects
231
+ _ensure_module_on_device(getattr(fo, 'unet', None), "UNet (from forge_objects)", cuda_device)
232
+ _ensure_module_on_device(getattr(fo, 'vae', None), "VAE (from forge_objects)", cuda_device)
233
+ _ensure_module_on_device(getattr(fo, 'clip', None), "CLIP (main from forge_objects)", cuda_device)
234
+ if hasattr(fo, 'clip') and fo.clip:
235
+ _ensure_module_on_device(getattr(fo.clip,'cond_stage_model', None), "CLIP cond_stage_model", cuda_device)
236
+
237
+ if hasattr(shared.sd_model, 'conditioner') and shared.sd_model.conditioner:
238
+ _ensure_module_on_device(shared.sd_model.conditioner, "Conditioner", cuda_device)
239
+ if hasattr(shared.sd_model.conditioner, 'embedders'):
240
+ for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
241
+ _ensure_module_on_device(embedder, f"Embedder {i}", cuda_device)
242
+
243
+ print("Forge: Device verification and correction attempt finished.")
244
+ else:
245
+ sd_models.load_model(chkpt_info_to_load)
246
+ print("Standard model reloaded.")
247
+ if torch.cuda.is_available() and shared.sd_model:
248
+ cuda_device = torch.device(devices.get_cuda_device_string())
249
+ _ensure_module_on_device(shared.sd_model, "shared.sd_model (main)", cuda_device)
250
+
251
+
252
+ state.is_model_unloaded_by_ext = False
253
+ return f"Model '{model_display_name}' reloaded successfully."
254
+
255
+ except Exception as e:
256
+ print(f"Error reloading model: {e}")
257
+ import traceback
258
+ traceback.print_exc()
259
+ lowvram.module_in_gpu = None
260
+ shared.sd_model = None
261
+ if forge and hasattr(model_data, 'sd_model'): model_data.sd_model = None
262
+ gc.collect()
263
+ if torch.cuda.is_available(): torch.cuda.empty_cache()
264
+ return f"Error reloading model: {e}. Model remains unloaded."
265
+
266
+
267
+ class UnloadReloadModelScript(scripts.Script):
268
+ def title(self):
269
+ return "Model Unload/Reload Util"
270
+
271
+ def show(self, is_img2img):
272
+ return scripts.AlwaysVisible
273
+
274
+ def ui(self, is_img2img):
275
+ with gr.Accordion(self.title(), open=False):
276
+ with gr.Row():
277
+ unload_button = gr.Button("Unload Current SD Model (Free VRAM)")
278
+ reload_button = gr.Button("Reload Last Unloaded SD Model")
279
+ status_text = gr.Textbox(label="Status", value="Ready.", interactive=False, lines=3, max_lines=3)
280
+
281
+ unload_button.click(fn=unload_model_logic, inputs=[], outputs=[status_text])
282
+ reload_button.click(fn=reload_last_model_logic, inputs=[], outputs=[status_text])
283
+ return [unload_button, reload_button, status_text]