Skip to content

Commit 7ea73a4

Browse files
committed
SD plugin up and running, but with tanked performances...... why
1 parent 10137ff commit 7ea73a4

78 files changed

Lines changed: 7900 additions & 823 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

core/cmdargs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
cargs = None
99

1010
parser = argparse.ArgumentParser()
11-
parser.add_argument("--dry", type=str, help="Only install and test the core, do not launch server.")
11+
parser.add_argument("--dry", action='store_true', help="Only install and test the core, do not launch server.")
12+
parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast")
1213

1314
# parser.add_argument("--gfpgan-dir", type=str, help="GFPGAN directory", default=('./src/gfpgan' if os.path.exists('./src/gfpgan') else './GFPGAN'))
1415
# parser.add_argument("--gfpgan-model", type=str, help="GFPGAN model file name", default=None)
@@ -23,7 +24,6 @@
2324
# parser.add_argument("--lowvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a lot of speed for very low VRM usage")
2425
# parser.add_argument("--always-batch-cond-uncond", action='store_true', help="disables cond/uncond batching that is enabled to save memory with --medvram or --lowvram")
2526
# parser.add_argument("--unload-gfpgan", action='store_true', help="does not do anything.")
26-
# parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast")
2727
# parser.add_argument("--share", action='store_true', help="use share=True for gradio and make the UI accessible through their site (doesn't work for me but you might have better luck)")
2828
# parser.add_argument("--ngrok", type=str, help="ngrok authtoken, alternative to gradio --share", default=None)
2929
# parser.add_argument("--codeformer-models-path", type=str, help="Path to directory with codeformer model file(s).", default=modeldir / 'Codeformer')

core/devicelib.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ def enable_tf32():
2626
torch.backends.cuda.matmul.allow_tf32 = True
2727
torch.backends.cudnn.allow_tf32 = True
2828

29+
def set_precision(precision):
30+
global dtype
31+
global dtype_vae
32+
33+
if precision == 'full':
34+
dtype = torch.float32
35+
dtype_vae = torch.float32
36+
elif precision == 'autocast':
37+
dtype = torch.float16
38+
dtype_vae = torch.float16
2939

3040
def randn(seed, shape):
3141
# Pytorch currently doesn't handle setting randomness correctly when the metal backend is used.
@@ -80,3 +90,5 @@ def autocast(enable=True):
8090
# device = device
8191

8292
device = get_optimal_device()
93+
94+
print(device)

core/jobs.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@
1414
class JobParams:
1515
def __init__(self, **kwargs):
1616
self.__dict__.update(kwargs)
17+
self.job: Job | None = None
1718

1819
@abstractmethod
1920
def get_plugin_impl(self):
20-
pass
21+
# TODO it's probably much better to do this in the plugin and then iterate plugins to see which one can handle this jobparams
22+
return None, None
2123

24+
@property
2225
def plugin(self):
23-
return self.job.plugin()
26+
return self.job.plugin
2427

2528
def on_start(self, job):
2629
pass
@@ -46,10 +49,12 @@ def __init__(self, plugin_id: str, plugin_func: str, parameters: JobParams):
4649
self.image = None
4750
self.timestamp: str = datetime.now().strftime("%Y%m%d%H%M%S") # shouldn't this return job_timestamp?
4851

52+
@property
4953
def plugin(self):
5054
import core.plugins
5155
return core.plugins.get(self.plugin_id)
5256

57+
@property
5358
def done(self):
5459
return self.progress == 1
5560

@@ -243,4 +248,4 @@ def is_processing(id):
243248

244249

245250
def is_any_processing():
246-
return len(queue.processing) > 0
251+
return len(queue.processing) > 0

core/plugins.py

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import importlib
2+
import os
23
import sys
34
import traceback
45
from pathlib import Path
56

67
# Constants
78
from core.jobs import JobParams
8-
from core.printing import printerr
9+
from core.printing import printerr, print_bp
910

1011
INIT_NONE = 0
1112
INIT_ENABLE = 1
@@ -29,9 +30,9 @@ def new_job(self, name, jobparams: JobParams):
2930
Return a new job
3031
"""
3132
from core import jobs
32-
jobparams.plugin = self
33-
return jobs.new_job(self.id, name, jobparams)
34-
33+
j = jobs.new_job(self.id, name, jobparams)
34+
j.plugin_id = self.id
35+
return j
3536
# The title of the script. This is what will be displayed in the dropdown menu.
3637
def title(self):
3738
raise NotImplementedError()
@@ -58,6 +59,9 @@ def install(self):
5859
def uninstall(self):
5960
pass
6061

62+
def load(self):
63+
pass
64+
6165
# Allows accessing script's attributes by indexing e.g. script['on_run_start']
6266
def get(self, varname):
6367
return getattr(self, varname)
@@ -122,15 +126,16 @@ def info(plugid):
122126
def load(path: Path):
123127
"""
124128
Manually load a plugin at the given path
129+
TODO this function is probably shite
125130
"""
126131
import inspect
127-
from types import ModuleType
128132

129133
# Find classes that extend Plugin in the module
130134
try:
131135
sys.path.append(path.as_posix())
132136
plugin_dirs.append(path)
133137

138+
# from types import ModuleType
134139
# # this is missing a bunch of module files for some reason...
135140
# mod = importlib.import_module(f'modules.{path.stem}')
136141
#
@@ -142,17 +147,24 @@ def load(path: Path):
142147
# plugins.append(plugin)
143148

144149
# TODO probably gonna have to detect by name instead (class & file name must be the same, and end with 'Plugin', e.g. StableDiffusionPlugin)
150+
151+
if not any(['plugin' in Path(f).name.lower() for f in os.listdir(path)]):
152+
return
153+
145154
for f in path.iterdir():
146155
if f.is_file() and f.suffix == '.py':
147156
mod = importlib.import_module(f'modules.{path.stem}.{f.stem}')
148157
for name, obj in inspect.getmembers(mod):
149-
if inspect.isclass(obj) and issubclass(obj, Plugin):
158+
if inspect.isclass(obj) and issubclass(obj, Plugin) and not obj == Plugin:
150159
# Instantiate the plugin
151-
print(f"Found plugin: {obj}")
160+
# print(f"Loaded plugin: {obj}")
152161
plugin = obj(dirpath=path)
153162
plugins.append(plugin)
154-
except:
155-
sys.path.remove(path.as_posix())
163+
except Exception as e:
164+
printerr(f"Couldn't load plugin {path.name}:")
165+
# Print the exception e and its full stacktrace
166+
excmsg = ''.join(traceback.format_exception(None, e, e.__traceback__))
167+
printerr(excmsg)
156168
plugin_dirs.remove(path)
157169

158170

@@ -168,7 +180,9 @@ def load_all(loaddir: Path):
168180
if p.is_dir() and not p.stem.startswith('__'):
169181
load(p)
170182

171-
print(f'Reloaded modules, {len(plugin_dirs)} found')
183+
print(f"Loaded {len(plugins)} plugins:")
184+
for plugin in plugins:
185+
print_bp(f"{plugin.id} ({plugin.dir})")
172186

173187

174188
def invoke(plugin, function, default=None, error=False, *args, **kwargs):
@@ -178,12 +192,15 @@ def invoke(plugin, function, default=None, error=False, *args, **kwargs):
178192
try:
179193
plug = get(plugin)
180194
if not plug:
181-
if error: printerr(f"Plugin {plugin} not found")
195+
if error:
196+
printerr(f"Plugin {plugin} not found")
182197
return default
183198

184-
attr = getattr(plug, function)
199+
attr = getattr(plug, function, None)
185200
if not attr:
186-
if error: printerr(f"Plugin {plugin} has no attribute {function}")
201+
if error:
202+
printerr(f"Plugin {plugin} has no attribute {function}")
203+
187204
return default
188205

189206
return attr(*args, **kwargs)
@@ -204,6 +221,6 @@ def broadcast(name, *args, **kwargs):
204221
"""
205222
Dispatch a function call to all plugins.
206223
"""
207-
print(f"broadcast({name}, {args}, {kwargs}) to {len(plugins)} plugins")
224+
# print(f"broadcast({name}, {args}, {kwargs}) to {len(plugins)} plugins")
208225
for plugin in plugins:
209226
invoke(plugin.id, name, None, False, *args, **kwargs)

core/printing.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import sys
22
import traceback
33

4+
def print_bp(msg):
5+
print(f' - {msg}')
46

57
def printerr(msg):
68
import sys

launch.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
import sys
66
import shlex
77

8+
import transformers
9+
810
from core.cmdargs import cargs
911
from core.paths import repodir
1012
from core.installing import is_installed, run, git, git_clone, run_python, run_pip, repo_dir, python
1113

1214
from core.paths import rootdir
13-
from modules.stable_diffusion.SDJob_txt2img import SDJob_txt2img
15+
from modules.stable_diffusion_auto1111.SDJob_txt2img import SDJob_txt2img
1416

1517
taming_transformers_commit_hash = os.environ.get('TAMING_TRANSFORMERS_COMMIT_HASH', "24268930bf1dce879235a7fddd0b2355b84d7ea6")
1618
torch_command = os.environ.get('TORCH_COMMAND', "pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113")
@@ -63,6 +65,12 @@ def sigint_handler(sig, frame):
6365

6466

6567
xformers_available = False
68+
transformers.logging.set_verbosity_error()
69+
try:
70+
from transformers import logging, CLIPModel
71+
logging.set_verbosity_error()
72+
except Exception:
73+
pass
6674

6775
if __name__ == "__main__":
6876
print_info()
@@ -83,6 +91,10 @@ def sigint_handler(sig, frame):
8391
sys.argv += args
8492
cargs = cmdargs.parser.parse_args(args)
8593

94+
# Prepare core
95+
# ----------------------------------------
96+
devicelib.set_precision(cargs.precision)
97+
8698
# Prepare plugin system
8799
# ----------------------------------------
88100
from core import plugins, options, paths
@@ -104,19 +116,26 @@ def sigint_handler(sig, frame):
104116

105117
# Dry run, only install and exit.
106118
# ----------------------------------------
119+
# plugins.broadcast("load")
120+
# plugins.job(SDJob_txt2img(prompt="Beautiful painting of an ultra contorted landscape by Greg Ruktowsky and Salvador Dali. airbrushed, 70s prog rock album cover, psychedelic, elaborate, complex",
121+
# cfg=7.75,
122+
# steps=22,
123+
# sampler='euler-a',
124+
# ))
125+
126+
# plugins.get("stable_diffusion_auto1111").txt2img()
127+
# plugins.get("stable_diffusion_auto2222").load()
128+
plugins.get("stable_diffusion_auto1111").load()
129+
130+
# plugins.get("stable_diffusion_auto2222").txt2img("Beautiful painting of an ultra contorted landscape by Greg Ruktowsky and Salvador Dali. airbrushed, 70s prog rock album cover, psychedelic, elaborate, complex")
131+
plugins.get("stable_diffusion_auto1111").txt2img(SDJob_txt2img(prompt="Beautiful painting of an ultra contorted landscape by Greg Ruktowsky and Salvador Dali. airbrushed, 70s prog rock album cover, psychedelic, elaborate, complex"))
132+
107133
if cargs.dry:
108134
print("Exiting because of --dry argument")
109135
exit(0)
110136

111137
# Start server
112138
# ----------------------------------------
113-
plugins.broadcast("launch") # doubt we need this
114-
115-
plugins.job(SDJob_txt2img(prompt="Beautiful painting of an ultra contorted landscape by Greg Ruktowsky and Salvador Dali. airbrushed, 70s prog rock album cover, psychedelic, elaborate, complex",
116-
cfg=7.75,
117-
steps=22,
118-
sampler='euler-a',
119-
))
120139

121140
install_webui()
122141
start_webui()

modules/params.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
hehe

modules/repositories/BLIP

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit 48211a1594f1321b00f14c9f7a5b4813144b2fb9

modules/repositories/CodeFormer

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit c5b4593074ba6214284d6acd5f1719b6c5d739af

modules/repositories/k-diffusion

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit f4e99857772fc3a126ba886aadf795a332774878

0 commit comments

Comments
 (0)