Skip to content

Commit 404434f

Browse files
committed
Made dependency installation cancellable and fixed some issues with clearing system dependencies
1 parent d45e6c8 commit 404434f

File tree

10 files changed

+125
-81
lines changed

10 files changed

+125
-81
lines changed

StableDiffusionTools/Content/Python/bridges/DiffusersBridge.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,10 @@ def InitModel(self, new_model_options, allow_nsfw, padding_mode):
224224
# Performance options for low VRAM gpus
225225
#self.pipe.enable_sequential_cpu_offload()
226226
self.pipe.enable_attention_slicing()
227-
self.pipe.unet = torch.compile(self.pipe.unet)
227+
try:
228+
self.pipe.unet = torch.compile(self.pipe.unet)
229+
except RuntimeError as e:
230+
print(f"WARNING: Couldn't compile unet for model. Exception given was '{e}'")
228231
#self.pipe.enable_xformers_memory_efficient_attention()
229232
if hasattr(self.pipe, "enable_model_cpu_offload"):
230233
self.pipe.enable_model_cpu_offload()
@@ -248,22 +251,14 @@ def InitModel(self, new_model_options, allow_nsfw, padding_mode):
248251
return result
249252

250253
def InitUpsampler(self):
251-
#upsampler = None
252-
#try:
253-
# upsampler = RealESRGANModel.from_pretrained("nateraw/real-esrgan")
254-
# upsampler = upsampler.to("cuda")
255-
#except Exception as e:
256-
# print("Could not load upsampler. Exception was ".format(e))
257-
#print(upsampler)
258-
#return upsampler
259-
upsampler = StableDiffusionUpscalePipeline.from_pretrained(
260-
"stabilityai/stable-diffusion-x4-upscaler", revision="fp16", torch_dtype=torch.float16
261-
)
262-
upsampler.enable_sequential_cpu_offload()
263-
upsampler.enable_attention_slicing()
254+
upsampler = None
255+
try:
256+
upsampler = RealESRGANModel.from_pretrained("nateraw/real-esrgan")
257+
upsampler = upsampler.to("cuda")
258+
except Exception as e:
259+
print("Could not load upsampler. Exception was ".format(e))
264260
return upsampler
265261

266-
267262
@unreal.ufunction(override=True)
268263
def ReleaseModel(self):
269264
if hasattr(self, "pipe"):
@@ -331,17 +326,11 @@ def GenerateImageFromStartImage(self, input):
331326
max_seed = abs(int((2**31) / 2) - 1)
332327
seed = random.randrange(0, max_seed) if input.options.seed < 0 else input.options.seed
333328

334-
# Collate prompts
335-
positive_prompts = " ".join([f"({split_p.strip()}){prompt.weight}" for prompt in input.options.positive_prompts for split_p in prompt.prompt.split(",")])
336-
negative_prompts = " ".join([f"({split_p.strip()}){prompt.weight}" for prompt in input.options.negative_prompts for split_p in prompt.prompt.split(",")])
337-
print(positive_prompts)
338-
print(negative_prompts)
339-
positive_prompt_tensors = self.compel.build_conditioning_tensor(positive_prompts if positive_prompts else "")
340-
negative_prompt_tensors = self.compel.build_conditioning_tensor(negative_prompts if negative_prompts else "")
341-
prompt_tensors = torch.cat(self.compel.pad_conditioning_tensors_to_same_length([positive_prompt_tensors, negative_prompt_tensors]))
329+
# Create prompt
330+
prompt_tensors = self.build_prompt_tensors(positive_prompts=input.options.positive_prompts, negative_prompts=input.options.negative_prompts, compel=self.compel)
342331

343332
with torch.inference_mode():
344-
with autocast("cuda", dtype=torch.float16):
333+
#with autocast("cuda", dtype=torch.float16):
345334
generator = torch.Generator(device="cpu")
346335
generator.manual_seed(seed)
347336
generation_args = {
@@ -422,6 +411,16 @@ def ImageProgressStep(self, step: int, timestep: int, latents: torch.FloatTensor
422411
if self.abort and self.executor:
423412
self.executor.stop()
424413

414+
def build_prompt_tensors(self, positive_prompts: list[unreal.Prompt], negative_prompts: list[unreal.Prompt], compel: Compel):
415+
# Collate prompts
416+
positive_prompts = " ".join([f"({split_p.strip()}){prompt.weight}" for prompt in positive_prompts for split_p in prompt.prompt.split(",")])
417+
negative_prompts = " ".join([f"({split_p.strip()}){prompt.weight}" for prompt in negative_prompts for split_p in prompt.prompt.split(",")])
418+
print(positive_prompts)
419+
print(negative_prompts)
420+
positive_prompt_tensors = compel.build_conditioning_tensor(positive_prompts if positive_prompts else "")
421+
negative_prompt_tensors = compel.build_conditioning_tensor(negative_prompts if negative_prompts else "")
422+
return torch.cat(compel.pad_conditioning_tensors_to_same_length([positive_prompt_tensors, negative_prompt_tensors]))
423+
425424
@unreal.ufunction(override=True)
426425
def StopImageGeneration(self):
427426
self.abort = True

StableDiffusionTools/Content/Python/bridges/DiffusersBridge_dependencies.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@ def MakeDependency(options):
1717
MakeDependency({"name":"accelerate", "version": "0.18.0"}),
1818
MakeDependency({"name":"diffusers", "version": "0.15.0"}),
1919
MakeDependency({"name":"compel", "version": "1.1.3"}),
20-
MakeDependency({"name":"opencv-python", "version":"4.7.0.72"})
20+
MakeDependency({"name":"opencv-python", "version":"4.7.0.72"}),
21+
MakeDependency({"name":"realesrgan", "version": "0.3.0"})
2122
]

StableDiffusionTools/Content/Python/dependency_manager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -126,17 +126,17 @@ def all_dependencies_installed(self):
126126
print(f"All dependencies installed? {dependencies_installed}")
127127
return dependencies_installed
128128

129-
def clear_all_dependencies(self, env_dir):
129+
def clear_all_dependencies(self, env_dir, reset_system_deps):
130130
# Remove external site-packages dir
131131
if os.path.exists(env_dir):
132132
shutil.rmtree(env_dir)
133133

134134
# Remove any leftover packages that are still in Unreal's base site-packages dir.
135-
# Only valid if we're upgrading our plugin from any version before 0.8.2
136-
if parse_version(self.get_plugin_version_name()) >= parse_version('0.8.2'):
135+
# Only really valid if we're upgrading our plugin from any version before 0.8.2
136+
if reset_system_deps:
137137
with open(Path(os.path.dirname(__file__)) / "requirements.txt") as f:
138-
requirements = f.read().splitlines()
139-
cmd = [f"{pythonpath}", '-m', 'pip', 'uninstall'] + requirements
138+
requirements = [package.split('==')[0] for package in f.read().splitlines()]
139+
cmd = [f"{pythonpath}", '-m', 'pip', 'uninstall'] + requirements + ['-y']
140140
cmd_string = " ".join(cmd)
141141
print(f"Uninstalling dependencies using command '{cmd_string}'")
142142
try:

StableDiffusionTools/Content/Python/init_unreal.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,11 @@ def load_manifests(manifest_dir):
7979

8080
# Nuke dependencies before loading them if we're trying to reset the editor dependencies
8181
reset_deps = dependency_options.get_editor_property("ClearDependenciesOnEditorRestart")
82-
if reset_deps:
82+
reset_system_deps = dependency_options.get_editor_property("ClearSystemDependenciesOnEditorRestart")
83+
84+
if reset_deps or reset_system_deps:
8385
print(f"Clearing python dependendencies")
84-
dep_manager.clear_all_dependencies(env_dir)
86+
dep_manager.clear_all_dependencies(env_dir, reset_system_deps)
8587

8688
# Flag dependencies as cleared so we don't keep clearing them every restart
8789
dep_manager.finished_clearing_dependencies()
Lines changed: 79 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,79 @@
1-
accelerate
2-
certifi
3-
charset_normalizer
4-
colorama
5-
compel
6-
cv2
7-
diffusers
8-
dotenv
9-
filelock
10-
ftfy
11-
functorch
12-
google
13-
grpc
14-
grpc_tools
15-
huggingface_hub
16-
idna
17-
importlib_metadata
18-
jinja2
19-
markupsafe
20-
mpmath
21-
networkx
22-
numpy
23-
nvfuser
24-
packaging
25-
PIL
26-
psutil
27-
pyparsing
28-
regex
29-
requests
30-
safetensors
31-
scipy
32-
scipy.libs
33-
setuptools
34-
share
35-
stability_sdk
36-
sympy
37-
tokenizers
38-
torch
39-
torchgen
40-
torchvision
41-
tqdm
42-
transformers
43-
urllib3
44-
wcwidth
45-
yaml
46-
zipp
1+
absl-py==1.4.0
2+
accelerate==0.18.0
3+
addict==2.4.0
4+
basicsr==1.4.2
5+
cachetools==5.3.0
6+
certifi==2022.12.7
7+
charset-normalizer==3.1.0
8+
colorama==0.4.6
9+
compel==1.1.3
10+
contourpy==1.0.7
11+
cycler==0.11.0
12+
diffusers==0.15.0
13+
facexlib==0.3.0
14+
filelock==3.11.0
15+
filterpy==1.4.5
16+
fonttools==4.39.3
17+
ftfy==6.1.1
18+
future==0.18.3
19+
gfpgan==1.3.8
20+
google-auth==2.17.3
21+
google-auth-oauthlib==1.0.0
22+
grpcio==1.53.0
23+
grpcio-tools==1.48.1
24+
huggingface-hub==0.13.4
25+
idna==3.4
26+
imageio==2.27.0
27+
importlib-metadata==6.4.1
28+
importlib-resources==5.12.0
29+
Jinja2==3.1.2
30+
kiwisolver==1.4.4
31+
lazy_loader==0.2
32+
llvmlite==0.39.1
33+
lmdb==1.4.1
34+
Markdown==3.4.3
35+
MarkupSafe==2.1.2
36+
matplotlib==3.7.1
37+
mpmath==1.3.0
38+
networkx==3.1
39+
numba==0.56.4
40+
numpy==1.24.2
41+
oauthlib==3.2.2
42+
opencv-python==4.7.0.72
43+
packaging==23.1
44+
Pillow==9.5.0
45+
protobuf==4.22.3
46+
psutil==5.9.4
47+
pyasn1==0.4.8
48+
pyasn1-modules==0.2.8
49+
pyparsing==3.0.9
50+
python-dateutil==2.8.2
51+
python-dotenv==1.0.0
52+
PyWavelets==1.4.1
53+
PyYAML==6.0
54+
realesrgan==0.3.0
55+
regex==2023.3.23
56+
requests==2.28.2
57+
requests-oauthlib==1.3.1
58+
rsa==4.9
59+
safetensors==0.3.0
60+
scikit-image==0.20.0
61+
scipy==1.10.1
62+
six==1.16.0
63+
stability-sdk==0.5.0
64+
sympy==1.11.1
65+
tb-nightly==2.13.0a20230414
66+
tensorboard-data-server==0.7.0
67+
tensorboard-plugin-wit==1.8.1
68+
tifffile==2023.4.12
69+
tokenizers==0.13.3
70+
torch==2.0.0+cu118
71+
torchvision==0.15.1+cu118
72+
tqdm==4.65.0
73+
transformers==4.28.1
74+
typing_extensions==4.5.0
75+
urllib3==1.26.15
76+
wcwidth==0.2.6
77+
Werkzeug==2.2.3
78+
yapf==0.32.0
79+
zipp==3.15.0
Binary file not shown.
Binary file not shown.

StableDiffusionTools/Source/StableDiffusionTools/Private/DependencyManager.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,20 @@ void UDependencyManager::RestartAndUpdateDependencies()
2525
UStableDiffusionBlueprintLibrary::RestartEditor();
2626
}
2727

28-
void UDependencyManager::ResetDependencies()
28+
void UDependencyManager::ResetDependencies(bool ClearSystemDeps)
2929
{
3030
auto Settings = GetMutableDefault<UDependencySettings>();
3131
Settings->ClearDependenciesOnEditorRestart = true;
32+
Settings->ClearSystemDependenciesOnEditorRestart = ClearSystemDeps;
3233
Settings->SaveConfig();
33-
RestartAndUpdateDependencies();
34+
//RestartAndUpdateDependencies();
3435
}
3536

3637
void UDependencyManager::FinishedClearingDependencies()
3738
{
3839
auto Settings = GetMutableDefault<UDependencySettings>();
3940
Settings->ClearDependenciesOnEditorRestart = false;
41+
Settings->ClearSystemDependenciesOnEditorRestart = false;
4042
Settings->SaveConfig();
4143
}
4244

@@ -45,6 +47,7 @@ void UDependencyManager::FinishedUpdatingDependencies()
4547
auto Settings = GetMutableDefault<UDependencySettings>();
4648
Settings->AutoLoadBridgeScripts = true;
4749
Settings->ClearDependenciesOnEditorRestart = false;
50+
Settings->ClearSystemDependenciesOnEditorRestart = false;
4851
Settings->AutoUpdateDependenciesOnStartup = false;
4952
Settings->SaveConfig();
5053
UStableDiffusionBlueprintLibrary::RestartEditor();

StableDiffusionTools/Source/StableDiffusionTools/Public/DependencyManager.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ class STABLEDIFFUSIONTOOLS_API UDependencyManager : public UObject
9797
void RestartAndUpdateDependencies();
9898

9999
UFUNCTION(BlueprintCallable, Category = "StableDiffusion|Dependencies")
100-
void ResetDependencies();
100+
void ResetDependencies(bool ClearSystemDeps = false);
101101

102102
UFUNCTION(BlueprintCallable, Category = "StableDiffusion|Dependencies")
103103
void FinishedClearingDependencies();

StableDiffusionTools/Source/StableDiffusionTools/Public/DependencySettings.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,10 @@ class STABLEDIFFUSIONTOOLS_API UDependencySettings : public UObject
3131
**/
3232
UPROPERTY(BlueprintReadWrite, config, EditAnywhere, Category = "Options")
3333
bool ClearDependenciesOnEditorRestart = false;
34+
35+
/**
36+
* Remove all downloaded python dependencies from Unreal's site-packages folder when the editor next starts.
37+
**/
38+
UPROPERTY(BlueprintReadWrite, config, EditAnywhere, Category = "Options")
39+
bool ClearSystemDependenciesOnEditorRestart = false;
3440
};

0 commit comments

Comments
 (0)