WhiteAiZ commited on
Commit
3abb63f
·
verified ·
1 Parent(s): db3b8c6

uptade forge classic

Browse files
README.md CHANGED
@@ -1,5 +1,9 @@
1
  <h1 align="center">Stable Diffusion WebUI Forge - Classic</h1>
2
 
 
 
 
 
3
  <p align="center"><img src="html\ui.webp" width=512 alt="UI"></p>
4
 
5
  <blockquote><i>
@@ -18,7 +22,7 @@ The name "Forge" is inspired by "Minecraft Forge". This project aims to become t
18
 
19
  <br>
20
 
21
- ## Features [Jul. 23]
22
  > Most base features of the original [Automatic1111 Webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) should still function
23
 
24
  #### New Features
@@ -61,6 +65,9 @@ The name "Forge" is inspired by "Minecraft Forge". This project aims to become t
61
  - [X] Persistent LoRA Patching
62
  - speed up LoRA loading in subsequent generations
63
  - see [Commandline](#by-classic)
 
 
 
64
  - [X] Implement new Samplers
65
  - *(ported from reForge Webui)*
66
  - [X] Implement Scheduler dropdown
@@ -177,6 +184,8 @@ The name "Forge" is inspired by "Minecraft Forge". This project aims to become t
177
  - [X] Run `text encoder` on CPU by default
178
  - [X] Fix `pydantic` Errors
179
  - [X] Fix `Soft Inpainting`
 
 
180
  - [X] Lint & Format
181
  - [X] Update `Pillow`
182
  - faster image processing
 
1
  <h1 align="center">Stable Diffusion WebUI Forge - Classic</h1>
2
 
3
+ <p align="center"><sup>
4
+ [ Classic | <a href="https://github.com/Haoming02/sd-webui-forge-classic/tree/neo#stable-diffusion-webui-forge---neo">Neo</a> ]
5
+ </sup></p>
6
+
7
  <p align="center"><img src="html\ui.webp" width=512 alt="UI"></p>
8
 
9
  <blockquote><i>
 
22
 
23
  <br>
24
 
25
+ ## Features [Aug. 13]
26
  > Most base features of the original [Automatic1111 Webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) should still function
27
 
28
  #### New Features
 
65
  - [X] Persistent LoRA Patching
66
  - speed up LoRA loading in subsequent generations
67
  - see [Commandline](#by-classic)
68
+ - [X] Patch LoRA in-place
69
+ - reduce VRAM usage when loading LoRA
70
+ - enable in **Settings/Extra Networks**
71
  - [X] Implement new Samplers
72
  - *(ported from reForge Webui)*
73
  - [X] Implement Scheduler dropdown
 
184
  - [X] Run `text encoder` on CPU by default
185
  - [X] Fix `pydantic` Errors
186
  - [X] Fix `Soft Inpainting`
187
+ - [X] Fix `Controllllite`
188
+ - [X] Fix `MultiDiffusion`
189
  - [X] Lint & Format
190
  - [X] Update `Pillow`
191
  - faster image processing
extensions-builtin/Lora/networks.py CHANGED
@@ -1,4 +1,3 @@
1
- import functools
2
  import os.path
3
  import re
4
 
@@ -9,7 +8,6 @@ from modules import errors, scripts, sd_models, shared
9
  import network
10
 
11
 
12
- @functools.lru_cache(maxsize=4, typed=False)
13
  def load_lora_state_dict(filename):
14
  return load_torch_file(filename, safe_load=True)
15
 
@@ -31,8 +29,6 @@ def get_networks_on_desk(names: list[str], *, tried: bool = True) -> list["netwo
31
 
32
 
33
  def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
34
- global lora_state_dict_cache
35
-
36
  current_sd = sd_models.model_data.get_sd_model()
37
  if current_sd is None:
38
  return
@@ -53,16 +49,18 @@ def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=No
53
 
54
  compiled_lora_targets = []
55
  for a, b, c in zip(networks_on_disk, unet_multipliers, te_multipliers):
56
- compiled_lora_targets.append([a.filename, b, c])
57
-
58
- compiled_lora_targets_hash = str(compiled_lora_targets)
59
 
60
- if current_sd.current_lora_hash == compiled_lora_targets_hash:
61
  return
62
 
63
- current_sd.current_lora_hash = compiled_lora_targets_hash
64
- current_sd.forge_objects.unet = current_sd.forge_objects_original.unet
65
- current_sd.forge_objects.clip = current_sd.forge_objects_original.clip
 
 
 
 
66
 
67
  for filename, strength_model, strength_clip in compiled_lora_targets:
68
  lora_sd = load_lora_state_dict(filename)
 
 
1
  import os.path
2
  import re
3
 
 
8
  import network
9
 
10
 
 
11
  def load_lora_state_dict(filename):
12
  return load_torch_file(filename, safe_load=True)
13
 
 
29
 
30
 
31
  def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
 
 
32
  current_sd = sd_models.model_data.get_sd_model()
33
  if current_sd is None:
34
  return
 
49
 
50
  compiled_lora_targets = []
51
  for a, b, c in zip(networks_on_disk, unet_multipliers, te_multipliers):
52
+ compiled_lora_targets.append((a.filename, b, c))
 
 
53
 
54
+ if shared.cached_lora_hash == compiled_lora_targets:
55
  return
56
 
57
+ shared.cached_lora_hash = compiled_lora_targets
58
+ current_sd.current_lora_hash = str(compiled_lora_targets)
59
+
60
+ if not bool(shared.cached_lora_hash):
61
+ del current_sd.forge_objects_after_applying_lora
62
+ current_sd.forge_objects_after_applying_lora = None
63
+ return
64
 
65
  for filename, strength_model, strength_clip in compiled_lora_targets:
66
  lora_sd = load_lora_state_dict(filename)
extensions-builtin/sd_forge_controlllite/lib_controllllite/lib_controllllite.py CHANGED
@@ -1,37 +1,24 @@
 
 
1
  import math
2
  import torch
3
 
4
 
5
  def extra_options_to_module_prefix(extra_options):
6
- # extra_options = {'transformer_index': 2, 'block_index': 8, 'original_shape': [2, 4, 128, 128], 'block': ('input', 7), 'n_heads': 20, 'dim_head': 64}
7
-
8
- # block is: [('input', 4), ('input', 5), ('input', 7), ('input', 8), ('middle', 0),
9
- # ('output', 0), ('output', 1), ('output', 2), ('output', 3), ('output', 4), ('output', 5)]
10
- # transformer_index is: [0, 1, 2, 3, 4, 5, 6, 7, 8], for each block
11
- # block_index is: 0-1 or 0-9, depends on the block
12
- # input 7 and 8, middle has 10 blocks
13
-
14
- # make module name from extra_options
15
  block = extra_options["block"]
16
  block_index = extra_options["block_index"]
17
  if block[0] == "input":
18
- module_pfx = (
19
- f"lllite_unet_input_blocks_{block[1]}_1_transformer_blocks_{block_index}"
20
- )
21
  elif block[0] == "middle":
22
  module_pfx = f"lllite_unet_middle_block_1_transformer_blocks_{block_index}"
23
  elif block[0] == "output":
24
- module_pfx = (
25
- f"lllite_unet_output_blocks_{block[1]}_1_transformer_blocks_{block_index}"
26
- )
27
  else:
28
  raise Exception("invalid block name")
29
  return module_pfx
30
 
31
 
32
- def load_control_net_lllite_patch(
33
- ctrl_sd, cond_image, multiplier, num_steps, start_percent, end_percent
34
- ):
35
  # calculate start and end step
36
  start_step = math.floor(num_steps * start_percent) if start_percent > 0 else 0
37
  end_step = math.floor(num_steps * end_percent) if end_percent > 0 else num_steps
@@ -70,16 +57,15 @@ def load_control_net_lllite_patch(
70
  start_step=start_step,
71
  end_step=end_step,
72
  )
73
- info = module.load_state_dict(weights)
74
  modules[module_name] = module
75
  if len(modules) == 1:
76
  module.is_first = True
77
 
78
- print(f"{len(modules)} modules")
79
 
80
  # cond imageをセットする
81
- cond_image = cond_image.permute(0, 3, 1, 2) # b,h,w,3 -> b,3,h,w
82
- cond_image = cond_image * 2.0 - 1.0 # 0-1 -> -1-+1
83
 
84
  for module in modules.values():
85
  module.set_cond_image(cond_image)
@@ -110,9 +96,9 @@ def load_control_net_lllite_patch(
110
 
111
  return q, k, v
112
 
113
- def to(self, device):
114
  for d in self.modules.keys():
115
- self.modules[d] = self.modules[d].to(device)
116
  return self
117
 
118
  return control_net_lllite_patch(modules)
@@ -142,41 +128,19 @@ class LLLiteModule(torch.nn.Module):
142
  self.is_first = False
143
 
144
  modules = []
145
- modules.append(
146
- torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)
147
- ) # to latent (from VAE) size*2
148
  if depth == 1:
149
  modules.append(torch.nn.ReLU(inplace=True))
150
- modules.append(
151
- torch.nn.Conv2d(
152
- cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0
153
- )
154
- )
155
  elif depth == 2:
156
  modules.append(torch.nn.ReLU(inplace=True))
157
- modules.append(
158
- torch.nn.Conv2d(
159
- cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0
160
- )
161
- )
162
  elif depth == 3:
163
  # kernel size 8は大きすぎるので、4にする / kernel size 8 is too large, so set it to 4
164
  modules.append(torch.nn.ReLU(inplace=True))
165
- modules.append(
166
- torch.nn.Conv2d(
167
- cond_emb_dim // 2,
168
- cond_emb_dim // 2,
169
- kernel_size=4,
170
- stride=4,
171
- padding=0,
172
- )
173
- )
174
  modules.append(torch.nn.ReLU(inplace=True))
175
- modules.append(
176
- torch.nn.Conv2d(
177
- cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0
178
- )
179
- )
180
 
181
  self.conditioning1 = torch.nn.Sequential(*modules)
182
 
@@ -186,9 +150,7 @@ class LLLiteModule(torch.nn.Module):
186
  torch.nn.ReLU(inplace=True),
187
  )
188
  self.mid = torch.nn.Sequential(
189
- torch.nn.Conv2d(
190
- mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0
191
- ),
192
  torch.nn.ReLU(inplace=True),
193
  )
194
  self.up = torch.nn.Sequential(
@@ -265,47 +227,13 @@ class LLLiteModule(torch.nn.Module):
265
 
266
 
267
  class LLLiteLoader:
268
- def __init__(self):
269
- pass
270
-
271
- @classmethod
272
- def INPUT_TYPES(s):
273
- return {
274
- "required": {
275
- "model": ("MODEL",),
276
- "model_name": None,
277
- "cond_image": ("IMAGE",),
278
- "strength": (
279
- "FLOAT",
280
- {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01},
281
- ),
282
- "steps": ("INT", {"default": 0, "min": 0, "max": 200, "step": 1}),
283
- "start_percent": (
284
- "FLOAT",
285
- {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1},
286
- ),
287
- "end_percent": (
288
- "FLOAT",
289
- {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1},
290
- ),
291
- }
292
- }
293
-
294
- RETURN_TYPES = ("MODEL",)
295
- FUNCTION = "load_lllite"
296
- CATEGORY = "loaders"
297
-
298
- def load_lllite(
299
- self, model, state_dict, cond_image, strength, steps, start_percent, end_percent
300
- ):
301
- # cond_image is b,h,w,3, 0-1
302
 
 
 
303
  model_lllite = model.clone()
304
- patch = load_control_net_lllite_patch(
305
- state_dict, cond_image, strength, steps, start_percent, end_percent
306
- )
307
  if patch is not None:
308
  model_lllite.set_model_attn1_patch(patch)
309
  model_lllite.set_model_attn2_patch(patch)
310
 
311
- return (model_lllite,)
 
1
+ # reference: https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI/blob/main/node_control_net_lllite.py
2
+
3
  import math
4
  import torch
5
 
6
 
7
  def extra_options_to_module_prefix(extra_options):
 
 
 
 
 
 
 
 
 
8
  block = extra_options["block"]
9
  block_index = extra_options["block_index"]
10
  if block[0] == "input":
11
+ module_pfx = f"lllite_unet_input_blocks_{block[1]}_1_transformer_blocks_{block_index}"
 
 
12
  elif block[0] == "middle":
13
  module_pfx = f"lllite_unet_middle_block_1_transformer_blocks_{block_index}"
14
  elif block[0] == "output":
15
+ module_pfx = f"lllite_unet_output_blocks_{block[1]}_1_transformer_blocks_{block_index}"
 
 
16
  else:
17
  raise Exception("invalid block name")
18
  return module_pfx
19
 
20
 
21
+ def load_control_net_lllite_patch(ctrl_sd, cond_image, multiplier, num_steps, start_percent, end_percent):
 
 
22
  # calculate start and end step
23
  start_step = math.floor(num_steps * start_percent) if start_percent > 0 else 0
24
  end_step = math.floor(num_steps * end_percent) if end_percent > 0 else num_steps
 
57
  start_step=start_step,
58
  end_step=end_step,
59
  )
60
+ module.load_state_dict(weights)
61
  modules[module_name] = module
62
  if len(modules) == 1:
63
  module.is_first = True
64
 
65
+ print(f"loaded {len(modules)} modules")
66
 
67
  # cond imageをセットする
68
+ cond_image = cond_image * 2.0 - 1.0 # 0.0 - 1.0 -> -1.0 - 1.0
 
69
 
70
  for module in modules.values():
71
  module.set_cond_image(cond_image)
 
96
 
97
  return q, k, v
98
 
99
+ def to(self, device=None, dtype=None):
100
  for d in self.modules.keys():
101
+ self.modules[d] = self.modules[d].to(device=device, dtype=dtype)
102
  return self
103
 
104
  return control_net_lllite_patch(modules)
 
128
  self.is_first = False
129
 
130
  modules = []
131
+ modules.append(torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size*2
 
 
132
  if depth == 1:
133
  modules.append(torch.nn.ReLU(inplace=True))
134
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
 
 
 
 
135
  elif depth == 2:
136
  modules.append(torch.nn.ReLU(inplace=True))
137
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
 
 
 
 
138
  elif depth == 3:
139
  # kernel size 8は大きすぎるので、4にする / kernel size 8 is too large, so set it to 4
140
  modules.append(torch.nn.ReLU(inplace=True))
141
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
 
 
 
 
 
 
 
 
142
  modules.append(torch.nn.ReLU(inplace=True))
143
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
 
 
 
 
144
 
145
  self.conditioning1 = torch.nn.Sequential(*modules)
146
 
 
150
  torch.nn.ReLU(inplace=True),
151
  )
152
  self.mid = torch.nn.Sequential(
153
+ torch.nn.Conv2d(mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
 
 
154
  torch.nn.ReLU(inplace=True),
155
  )
156
  self.up = torch.nn.Sequential(
 
227
 
228
 
229
  class LLLiteLoader:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
+ @staticmethod
232
+ def load_lllite(model, state_dict, cond_image, strength, steps, start_percent, end_percent):
233
  model_lllite = model.clone()
234
+ patch = load_control_net_lllite_patch(state_dict, cond_image, strength, steps, start_percent, end_percent)
 
 
235
  if patch is not None:
236
  model_lllite.set_model_attn1_patch(patch)
237
  model_lllite.set_model_attn2_patch(patch)
238
 
239
+ return model_lllite
extensions-builtin/sd_forge_controlllite/scripts/forge_controllllite.py CHANGED
@@ -3,36 +3,31 @@ from modules_forge.supported_controlnet import ControlModelPatcher
3
  from lib_controllllite.lib_controllllite import LLLiteLoader
4
 
5
 
6
- opLLLiteLoader = LLLiteLoader().load_lllite
7
-
8
-
9
  class ControlLLLitePatcher(ControlModelPatcher):
 
 
 
 
10
  @staticmethod
11
  def try_build_from_state_dict(state_dict, ckpt_path):
12
  if not any("lllite" in k for k in state_dict.keys()):
13
  return None
14
  return ControlLLLitePatcher(state_dict)
15
 
16
- def __init__(self, state_dict):
17
- super().__init__()
18
- self.state_dict = state_dict
19
- return
20
-
21
- def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
22
  unet = process.sd_model.forge_objects.unet
23
 
24
- unet = opLLLiteLoader(
25
  model=unet,
26
  state_dict=self.state_dict,
27
- cond_image=cond.movedim(1, -1),
28
  strength=self.strength,
29
  steps=process.steps,
30
  start_percent=self.start_percent,
31
  end_percent=self.end_percent,
32
- )[0]
33
 
34
  process.sd_model.forge_objects.unet = unet
35
- return
36
 
37
 
38
  add_supported_control_model(ControlLLLitePatcher)
 
3
  from lib_controllllite.lib_controllllite import LLLiteLoader
4
 
5
 
 
 
 
6
  class ControlLLLitePatcher(ControlModelPatcher):
7
+ def __init__(self, state_dict):
8
+ super().__init__()
9
+ self.state_dict = state_dict
10
+
11
  @staticmethod
12
  def try_build_from_state_dict(state_dict, ckpt_path):
13
  if not any("lllite" in k for k in state_dict.keys()):
14
  return None
15
  return ControlLLLitePatcher(state_dict)
16
 
17
+ def process_before_every_sampling(self, process, cond, *args, **kwargs):
 
 
 
 
 
18
  unet = process.sd_model.forge_objects.unet
19
 
20
+ unet = LLLiteLoader.load_lllite(
21
  model=unet,
22
  state_dict=self.state_dict,
23
+ cond_image=cond,
24
  strength=self.strength,
25
  steps=process.steps,
26
  start_percent=self.start_percent,
27
  end_percent=self.end_percent,
28
+ )
29
 
30
  process.sd_model.forge_objects.unet = unet
 
31
 
32
 
33
  add_supported_control_model(ControlLLLitePatcher)
extensions-builtin/sd_forge_controlnet/lib_controlnet/utils.py CHANGED
@@ -42,62 +42,6 @@ def get_state_dict(d):
42
  return d.get("state_dict", d)
43
 
44
 
45
- def ndarray_lru_cache(max_size: int = 128, typed: bool = False):
46
- """
47
- Decorator to enable caching for functions with numpy array arguments.
48
- Numpy arrays are mutable, and thus not directly usable as hash keys.
49
-
50
- The idea here is to wrap the incoming arguments with type `np.ndarray`
51
- as `HashableNpArray` so that `lru_cache` can correctly handles `np.ndarray`
52
- arguments.
53
-
54
- `HashableNpArray` functions exactly the same way as `np.ndarray` except
55
- having `__hash__` and `__eq__` overridden.
56
- """
57
-
58
- def decorator(func: Callable):
59
- """The actual decorator that accept function as input"""
60
-
61
- class HashableNpArray(np.ndarray):
62
- def __new__(cls, input_array):
63
- # Input array is an instance of ndarray
64
- # The view makes the input array and returned array share the same data
65
- obj = np.asarray(input_array).view(cls)
66
- return obj
67
-
68
- def __eq__(self, other) -> bool:
69
- return np.array_equal(self, other)
70
-
71
- def __hash__(self):
72
- # Hash the bytes representing the data of the array
73
- return hash(self.tobytes())
74
-
75
- @functools.lru_cache(maxsize=max_size, typed=typed)
76
- def cached_func(*args, **kwargs):
77
- """This function only accepts `HashableNpArray` as input params"""
78
- return func(*args, **kwargs)
79
-
80
- # Preserves original function.__name__ and __doc__
81
- @functools.wraps(func)
82
- def decorated_func(*args, **kwargs):
83
- """The decorated function that delegates the original function"""
84
-
85
- def convert_item(item):
86
- if isinstance(item, np.ndarray):
87
- return HashableNpArray(item)
88
- if isinstance(item, tuple):
89
- return tuple(convert_item(i) for i in item)
90
- return item
91
-
92
- args = [convert_item(arg) for arg in args]
93
- kwargs = {k: convert_item(arg) for k, arg in kwargs.items()}
94
- return cached_func(*args, **kwargs)
95
-
96
- return decorated_func
97
-
98
- return decorator
99
-
100
-
101
  def timer_decorator(func):
102
  """Time the decorated function and output the result to debug logger"""
103
  if logger.level != logging.DEBUG:
@@ -129,7 +73,7 @@ class TimeMeta(type):
129
  return super().__new__(cls, name, bases, attrs)
130
 
131
 
132
- @functools.lru_cache(1, False)
133
  def _blank_mask() -> str:
134
  with io.BytesIO() as buffer:
135
  black = Image.new("RGB", (4, 4))
@@ -143,9 +87,7 @@ def svg_preprocess(inputs: dict, preprocess: Callable):
143
  return None
144
 
145
  if svgSupport and inputs["image"].startswith("data:image/svg+xml;base64,"):
146
- svg_data = base64.b64decode(
147
- inputs["image"].replace("data:image/svg+xml;base64,", "")
148
- )
149
  drawing = svg2rlg(io.BytesIO(svg_data))
150
  png_data = renderPM.drawToString(drawing, fmt="PNG")
151
  encoded_string = base64.b64encode(png_data)
@@ -178,9 +120,7 @@ def align_dim_latent(x: int) -> int:
178
  return (x // 8) * 8
179
 
180
 
181
- def prepare_mask(
182
- mask: Image.Image, p: processing.StableDiffusionProcessing
183
- ) -> Image.Image:
184
  """
185
  Prepare an image mask for the inpainting process.
186
 
@@ -333,31 +273,21 @@ def crop_and_resize_image(detected_map, resize_mode, h, w, fill_border_with_255=
333
  ],
334
  axis=0,
335
  )
336
- high_quality_border_color = np.median(borders, axis=0).astype(
337
- detected_map.dtype
338
- )
339
  if fill_border_with_255:
340
  high_quality_border_color = np.zeros_like(high_quality_border_color) + 255
341
- high_quality_background = np.tile(
342
- high_quality_border_color[None, None], [h, w, 1]
343
- )
344
- detected_map = high_quality_resize(
345
- detected_map, (safeint(old_w * k), safeint(old_h * k))
346
- )
347
  new_h, new_w, _ = detected_map.shape
348
  pad_h = max(0, (h - new_h) // 2)
349
  pad_w = max(0, (w - new_w) // 2)
350
- high_quality_background[pad_h : pad_h + new_h, pad_w : pad_w + new_w] = (
351
- detected_map
352
- )
353
  detected_map = high_quality_background
354
  detected_map = safe_numpy(detected_map)
355
  return detected_map
356
  else:
357
  k = max(k0, k1)
358
- detected_map = high_quality_resize(
359
- detected_map, (safeint(old_w * k), safeint(old_h * k))
360
- )
361
  new_h, new_w, _ = detected_map.shape
362
  pad_h = max(0, (new_h - h) // 2)
363
  pad_w = max(0, (new_w - w) // 2)
 
42
  return d.get("state_dict", d)
43
 
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def timer_decorator(func):
46
  """Time the decorated function and output the result to debug logger"""
47
  if logger.level != logging.DEBUG:
 
73
  return super().__new__(cls, name, bases, attrs)
74
 
75
 
76
+ @functools.lru_cache(maxsize=1, typed=False)
77
  def _blank_mask() -> str:
78
  with io.BytesIO() as buffer:
79
  black = Image.new("RGB", (4, 4))
 
87
  return None
88
 
89
  if svgSupport and inputs["image"].startswith("data:image/svg+xml;base64,"):
90
+ svg_data = base64.b64decode(inputs["image"].replace("data:image/svg+xml;base64,", ""))
 
 
91
  drawing = svg2rlg(io.BytesIO(svg_data))
92
  png_data = renderPM.drawToString(drawing, fmt="PNG")
93
  encoded_string = base64.b64encode(png_data)
 
120
  return (x // 8) * 8
121
 
122
 
123
+ def prepare_mask(mask: Image.Image, p: processing.StableDiffusionProcessing) -> Image.Image:
 
 
124
  """
125
  Prepare an image mask for the inpainting process.
126
 
 
273
  ],
274
  axis=0,
275
  )
276
+ high_quality_border_color = np.median(borders, axis=0).astype(detected_map.dtype)
 
 
277
  if fill_border_with_255:
278
  high_quality_border_color = np.zeros_like(high_quality_border_color) + 255
279
+ high_quality_background = np.tile(high_quality_border_color[None, None], [h, w, 1])
280
+ detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
 
 
 
 
281
  new_h, new_w, _ = detected_map.shape
282
  pad_h = max(0, (h - new_h) // 2)
283
  pad_w = max(0, (w - new_w) // 2)
284
+ high_quality_background[pad_h : pad_h + new_h, pad_w : pad_w + new_w] = detected_map
 
 
285
  detected_map = high_quality_background
286
  detected_map = safe_numpy(detected_map)
287
  return detected_map
288
  else:
289
  k = max(k0, k1)
290
+ detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
 
 
291
  new_h, new_w, _ = detected_map.shape
292
  pad_h = max(0, (new_h - h) // 2)
293
  pad_w = max(0, (new_w - w) // 2)
extensions-builtin/sd_forge_controlnet/scripts/controlnet.py CHANGED
@@ -27,7 +27,7 @@ from modules_forge.supported_controlnet import ControlModelPatcher
27
  global_state.update_controlnet_filenames()
28
 
29
 
30
- @functools.lru_cache(maxsize=shared.opts.data.get("control_net_model_cache_size", 5))
31
  def cached_controlnet_loader(filename):
32
  return try_load_supported_control_model(filename)
33
 
@@ -534,7 +534,7 @@ def on_ui_settings():
534
  3,
535
  "Number of Models to Cache in Memory",
536
  gr.Slider,
537
- {"minimum": 1, "maximum": 10, "step": 1},
538
  section=section,
539
  category_id=category_id,
540
  ).needs_reload_ui(),
 
27
  global_state.update_controlnet_filenames()
28
 
29
 
30
+ @functools.lru_cache(maxsize=getattr(shared.opts, "control_net_model_cache_size", 1))
31
  def cached_controlnet_loader(filename):
32
  return try_load_supported_control_model(filename)
33
 
 
534
  3,
535
  "Number of Models to Cache in Memory",
536
  gr.Slider,
537
+ {"minimum": 0, "maximum": 10, "step": 1},
538
  section=section,
539
  category_id=category_id,
540
  ).needs_reload_ui(),
extensions-builtin/sd_forge_multidiffusion/lib_multidiffusion/tiled_diffusion.py CHANGED
@@ -13,6 +13,7 @@ from numpy import exp, pi, sqrt
13
  from torch import Tensor
14
 
15
  from ldm_patched.modules.controlnet import ControlNet, T2IAdapter
 
16
  from ldm_patched.modules.model_base import BaseModel
17
  from ldm_patched.modules.model_management import current_loaded_models, get_torch_device, load_models_gpu
18
  from ldm_patched.modules.model_patcher import ModelPatcher
@@ -251,7 +252,9 @@ class AbstractDiffusion:
251
  self.control_tensor_batch[param_id][batch_id] = control_tile
252
 
253
  def process_controlnet(self, x_noisy, c_in: dict, cond_or_uncond: list, bboxes, batch_size: int, batch_id: int, shifts=None, shift_condition=None):
254
- control: ControlNet = c_in["control"]
 
 
255
  param_id = -1
256
  tuple_key = tuple(cond_or_uncond) + tuple(x_noisy.shape)
257
  while control is not None:
@@ -271,11 +274,7 @@ class AbstractDiffusion:
271
  del control.cond_hint
272
  control.cond_hint = None
273
  compression_ratio = control.compression_ratio
274
- if control.vae is not None:
275
- compression_ratio *= control.vae.downscale_ratio
276
- else:
277
- if control.latent_format is not None:
278
- raise ValueError("This Controlnet needs a VAE but none was provided, please use a ControlNetApply node with a VAE input and connect it.")
279
  PH, PW = self.h * compression_ratio, self.w * compression_ratio
280
 
281
  device = getattr(control, "device", x_noisy.device)
@@ -405,9 +404,9 @@ class MultiDiffusion(AbstractDiffusion):
405
  v = repeat_to_batch_size(v, x_tile.shape[0])
406
  c_tile[k] = v
407
 
408
- if "control" in c_in:
409
  self.process_controlnet(x_tile, c_in, cond_or_uncond, bboxes, N, batch_id)
410
- c_tile["control"] = c_in["control"].get_control_orig(x_tile, t_tile, c_tile, len(cond_or_uncond))
411
 
412
  x_tile_out = model_function(x_tile, t_tile, **c_tile)
413
 
@@ -496,9 +495,9 @@ class MixtureOfDiffusers(AbstractDiffusion):
496
  v = repeat_to_batch_size(v, x_tile.shape[0])
497
  c_tile[k] = v
498
 
499
- if "control" in c_in:
500
  self.process_controlnet(x_tile, c_in, cond_or_uncond, bboxes, N, batch_id)
501
- c_tile["control"] = c_in["control"].get_control_orig(x_tile, t_tile, c_tile, len(cond_or_uncond))
502
 
503
  x_tile_out = model_function(x_tile, t_tile, **c_tile)
504
 
 
13
  from torch import Tensor
14
 
15
  from ldm_patched.modules.controlnet import ControlNet, T2IAdapter
16
+ from ldm_patched.modules.latent_formats import SD15, SDXL
17
  from ldm_patched.modules.model_base import BaseModel
18
  from ldm_patched.modules.model_management import current_loaded_models, get_torch_device, load_models_gpu
19
  from ldm_patched.modules.model_patcher import ModelPatcher
 
252
  self.control_tensor_batch[param_id][batch_id] = control_tile
253
 
254
  def process_controlnet(self, x_noisy, c_in: dict, cond_or_uncond: list, bboxes, batch_size: int, batch_id: int, shifts=None, shift_condition=None):
255
+ from modules.shared import sd_model
256
+
257
+ control: ControlNet = c_in["control_model"]
258
  param_id = -1
259
  tuple_key = tuple(cond_or_uncond) + tuple(x_noisy.shape)
260
  while control is not None:
 
274
  del control.cond_hint
275
  control.cond_hint = None
276
  compression_ratio = control.compression_ratio
277
+ control.latent_format = SDXL() if sd_model.is_sdxl else SD15()
 
 
 
 
278
  PH, PW = self.h * compression_ratio, self.w * compression_ratio
279
 
280
  device = getattr(control, "device", x_noisy.device)
 
404
  v = repeat_to_batch_size(v, x_tile.shape[0])
405
  c_tile[k] = v
406
 
407
+ if "control_model" in c_in:
408
  self.process_controlnet(x_tile, c_in, cond_or_uncond, bboxes, N, batch_id)
409
+ c_tile["control"] = c_in["control_model"].get_control(x_tile, t_tile, c_tile, len(cond_or_uncond))
410
 
411
  x_tile_out = model_function(x_tile, t_tile, **c_tile)
412
 
 
495
  v = repeat_to_batch_size(v, x_tile.shape[0])
496
  c_tile[k] = v
497
 
498
+ if "control_model" in c_in:
499
  self.process_controlnet(x_tile, c_in, cond_or_uncond, bboxes, N, batch_id)
500
+ c_tile["control"] = c_in["control_model"].get_control(x_tile, t_tile, c_tile, len(cond_or_uncond))
501
 
502
  x_tile_out = model_function(x_tile, t_tile, **c_tile)
503
 
javascript/hints.js CHANGED
@@ -1,185 +1,69 @@
1
  // mouseover tooltips for various UI elements
2
 
3
- var titles = {
4
- "Sampling steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results",
5
- "Sampling method": "Which algorithm to use to produce the image",
6
- "GFPGAN": "Restore low quality faces using GFPGAN neural network",
7
- "Euler a": "Euler Ancestral - very creative, each can get a completely different picture depending on step count, setting steps higher than 30-40 does not help",
8
- "DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
9
- "UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
10
- "DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
11
-
12
- "\u{1F4D0}": "Auto detect size from img2img",
13
- "Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
14
- "Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
15
- "CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
16
- "Rescale CFG": "Reduce the high-contrast burnt color caused by high CFG; mainly for v-pred checkpoints",
17
- "Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result",
18
- "\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
19
- "\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomized",
20
- "\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
21
- "\u{1f4c2}": "Open images output directory",
22
- "\u{1f4be}": "Save style",
23
- "\u{1f5d1}\ufe0f": "Clear prompt",
24
- "\u{1f4cb}": "Apply selected styles to current prompt",
25
- "\u{1f4d2}": "Paste available values into the field",
26
- "\u{1f3b4}": "Show/hide extra networks",
27
- "\u{1f300}": "Restore progress",
28
-
29
- "Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
30
- "SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
31
-
32
- "Just resize": "Resize image to target resolution. Unless height and width match, you will get incorrect aspect ratio.",
33
- "Crop and resize": "Resize the image so that entirety of target resolution is filled with the image. Crop parts that stick out.",
34
- "Resize and fill": "Resize the image so that entirety of image is inside target resolution. Fill empty space with image's colors.",
35
-
36
- "Mask blur": "How much to blur the mask before processing, in pixels.",
37
- "Masked content": "What to put inside the masked area before processing it with Stable Diffusion.",
38
- "fill": "fill it with colors of the image",
39
- "original": "keep whatever was there originally",
40
- "latent noise": "fill it with latent space noise",
41
- "latent nothing": "fill it with latent space zeroes",
42
- "Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
43
-
44
- "Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
45
-
46
- "Skip": "Stop processing current image and continue processing.",
47
- "Interrupt": "Stop processing images and return any results accumulated so far.",
48
- "Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
49
-
50
- "X values": "Separate values for X axis using commas.",
51
- "Y values": "Separate values for Y axis using commas.",
52
-
53
- "None": "Do not do anything special",
54
- "Prompt matrix": "Separate prompts into parts using vertical pipe character (|) and the script will create a picture for every combination of them (except for the first part, which will be present in all combinations)",
55
- "X/Y/Z plot": "Create grid(s) where images will have different parameters. Use inputs below to specify which parameters will be shared by columns and rows",
56
-
57
- "Prompt S/R": "Separate a list of words with commas, and the first word will be used as a keyword: script will search for this word in the prompt, and replace it with others",
58
- "Prompt order": "Separate a list of words with commas, and the script will make a variation of prompt with those words for their every possible order",
59
-
60
- "Tiling": "Produce an image that can be tiled.",
61
- "Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.",
62
-
63
- "Variation seed": "Seed of a different picture to be mixed into the generation.",
64
- "Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).",
65
- "Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
66
- "Resize seed from width": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
67
-
68
- "Images filename pattern": "Use tags like [seed] and [date] to define how filenames for images are chosen. Leave empty for default.",
69
- "Directory name pattern": "Use tags like [seed] and [date] to define how subdirectories for images and grids are chosen. Leave empty for default.",
70
- "Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
71
-
72
- "Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
73
- "Loops": "How many times to process an image. Each output is used as the input of the next loop. If set to 1, behavior will be as if this script were not used.",
74
- "Final denoising strength": "The denoising strength for the final loop of each image in the batch.",
75
- "Denoising strength curve": "The denoising curve controls the rate of denoising strength change each loop. Aggressive: Most of the change will happen towards the start of the loops. Linear: Change will be constant through all loops. Lazy: Most of the change will happen towards the end of the loops.",
76
-
77
- "Style 1": "Style to apply; styles have components for both positive and negative prompts and apply to both",
78
- "Style 2": "Style to apply; styles have components for both positive and negative prompts and apply to both",
79
- "Apply style": "Insert selected styles into prompt fields",
80
- "Create style": "Save current prompts as a style. If you add the token {prompt} to the text, the style uses that as a placeholder for your prompt when you use the style in the future.",
81
-
82
- "Checkpoint name": "Loads weights from checkpoint before making images. You can either use hash or a part of filename (as seen in settings) for checkpoint name. Recommended to use with Y axis for less switching.",
83
- "Inpainting conditioning mask strength": "Only applies to inpainting models. Determines how strongly to mask off the original image for inpainting and img2img. 1.0 means fully masked, which is the default behaviour. 0.0 means a fully unmasked conditioning. Lower values will help preserve the overall composition of the image, but will struggle with large changes.",
84
-
85
- "Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
86
-
87
- "Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
88
- "Filename join string": "This string will be used to join split words into a single line if the option above is enabled.",
89
-
90
- "Quicksettings list": "List of setting names, separated by commas, for settings that should go to the quick access bar at the top, rather than the usual setting tab. See modules/shared.py for setting names. Requires restarting to apply.",
91
-
92
- "Weighted sum": "Result = A * (1 - M) + B * M",
93
- "Add difference": "Result = A + (B - C) * M",
94
- "No interpolation": "Result = A",
95
-
96
- "Initialization text": "If the number of tokens is more than the number of vectors, some may be skipped.\nLeave the textbox empty to start with zeroed out vectors",
97
- "Learning rate": "How fast should training go. Low values will take longer to train, high values may fail to converge (not generate accurate results) and/or may break the embedding (This has happened if you see Loss: nan in the training info textbox. If this happens, you need to manually restore your embedding from an older not-broken backup).\n\nYou can set a single numeric value, or multiple learning rates using the syntax:\n\n rate_1:max_steps_1, rate_2:max_steps_2, ...\n\nEG: 0.005:100, 1e-3:1000, 1e-5\n\nWill train with rate of 0.005 for first 100 steps, then 1e-3 until 1000 steps, then 1e-5 for all remaining steps.",
98
-
99
- "Clip skip": "Early stopping parameter for CLIP model; 1 is stop at last layer as usual, 2 is stop at penultimate layer, etc.",
100
-
101
- "Approx NN": "Cheap neural network approximation. Very fast compared to VAE, but produces pictures with 4 times smaller horizontal/vertical resolution and lower quality.",
102
- "Approx cheap": "Very cheap approximation. Very fast compared to VAE, but produces pictures with 8 times smaller horizontal/vertical resolution and extremely low quality.",
103
-
104
- "Hires. fix": "Use a two step process to partially create an image at smaller resolution, upscale, and then improve details in it without changing composition",
105
- "Hires steps": "Number of sampling steps for upscaled picture. If 0, uses same as for original.",
106
- "Upscale by": "Adjusts the size of the image by multiplying the original width and height by the selected value. Ignored if either Resize width to or Resize height to are non-zero.",
107
- "Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.",
108
- "Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
109
- "Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.",
110
- "Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order listed.",
111
- "Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
112
  };
113
 
114
  function updateTooltip(element) {
115
- if (element.title) return; // already has a title
116
 
117
- let text = element.textContent;
118
  let tooltip = localization[titles[text]] || titles[text];
119
 
120
- if (!tooltip) {
121
- let value = element.value;
122
- if (value) tooltip = localization[titles[value]] || titles[value];
123
- }
124
-
125
- if (!tooltip) {
126
- // Gradio dropdown options have `data-value`.
127
- let dataValue = element.dataset.value;
128
- if (dataValue) tooltip = localization[titles[dataValue]] || titles[dataValue];
129
- }
130
 
131
- if (!tooltip) {
132
- for (const c of element.classList) {
133
- if (c in titles) {
134
- tooltip = localization[titles[c]] || titles[c];
135
- break;
136
- }
137
- }
138
- }
139
-
140
- if (tooltip) {
141
- element.title = tooltip;
142
- }
143
  }
144
 
145
- // Nodes to check for adding tooltips.
146
  const tooltipCheckNodes = new Set();
147
- // Timer for debouncing tooltip check.
148
  let tooltipCheckTimer = null;
149
 
150
  function processTooltipCheckNodes() {
151
- for (const node of tooltipCheckNodes) {
152
  updateTooltip(node);
153
- }
154
  tooltipCheckNodes.clear();
155
  }
156
 
157
  onUiUpdate(function (mutationRecords) {
158
  for (const record of mutationRecords) {
159
- if (record.type === "childList" && record.target.classList.contains("options")) {
160
- // This smells like a Gradio dropdown menu having changed,
161
- // so let's enqueue an update for the input element that shows the current value.
162
- let wrap = record.target.parentNode;
163
- let input = wrap?.querySelector("input");
164
- if (input) {
165
- input.title = ""; // So we'll even have a chance to update it.
166
- tooltipCheckNodes.add(input);
167
- }
168
- }
169
  for (const node of record.addedNodes) {
170
  if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains("hide")) {
171
  if (!node.title) {
172
- if (
173
- node.tagName === "SPAN" ||
174
- node.tagName === "BUTTON" ||
175
- node.tagName === "P" ||
176
- node.tagName === "INPUT" ||
177
- (node.tagName === "LI" && node.classList.contains("item")) // Gradio dropdown item
178
- ) {
179
  tooltipCheckNodes.add(node);
180
- }
181
  }
182
- node.querySelectorAll('span, button, p').forEach(n => tooltipCheckNodes.add(n));
183
  }
184
  }
185
  }
@@ -189,13 +73,11 @@ onUiUpdate(function (mutationRecords) {
189
  }
190
  });
191
 
192
- onUiLoaded(function () {
193
  for (const comp of window.gradio_config.components) {
194
  if (comp.props.webui_tooltip && comp.props.elem_id) {
195
  const elem = gradioApp().getElementById(comp.props.elem_id);
196
- if (elem) {
197
- elem.title = comp.props.webui_tooltip;
198
- }
199
  }
200
  }
201
  });
 
1
  // mouseover tooltips for various UI elements
2
 
3
+ const titles = {
4
+ "Sampling Method": "The algorithm used to refine each step of the image",
5
+ "Schedule Type": "The algorithm used to adjust the magnitude of refinement",
6
+ "Sampling Steps": "The number of times the image is iteratively refined",
7
+
8
+ "Batch Count": "How many batches of images to generate (in sequence)",
9
+ "Batch Size": "How many images to generate in a single batch (in parallel)",
10
+
11
+ "CFG Scale": "The strength used to calculate conditionings",
12
+ "Rescale CFG": "Reduce the high-contrast burnt-color effects (mainly for v-pred checkpoints)",
13
+ "MaHiRo": "An alternative algorithm used for CFG calculation",
14
+
15
+ "Seed": 'Given the same prompts and parameters, you "should" generate the same image if the Seed is also the same',
16
+
17
+ "Just resize": "Resize input image directly to target resolution",
18
+ "Crop and resize": "Resize the image while maintaining the aspect ratio; crop the excessive parts",
19
+ "Resize and fill": "Resize the image while maintaining the aspect ratio; fill the empty parts with neighboring colors",
20
+
21
+ "Mask blur": "How much feathering to apply to the mask (in pixels)",
22
+ "fill": "Fill the masked areas with neighboring colors",
23
+ "original": "Keep whatever was within the masked areas",
24
+ "latent noise": "Fill the masked areas with noise (requires high Denoising strength)",
25
+ "latent nothing": "Fill the masked areas with zero values (requires high Denoising strength)",
26
+
27
+ "Denoising strength": "How strong should the image be changed",
28
+
29
+ "Hires. fix": "Automatically perform an additional pass of img2img",
30
+ "Hires steps": "Sampling Steps for the img2img pass; use original if 0",
31
+ "Upscale by": "Multiply the txt2img dimension by this ratio, to serve as the target dimension",
32
+ "Resize width to": 'Resize image to this width; use "Upscale by" if 0',
33
+ "Resize height to": 'Resize image to this height; use "Upscale by" if 0',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  };
35
 
36
  function updateTooltip(element) {
37
+ if (element.title) return;
38
 
39
+ const text = element.textContent || element.value;
40
  let tooltip = localization[titles[text]] || titles[text];
41
 
42
+ if (!tooltip) return;
43
+ element.title = tooltip;
 
 
 
 
 
 
 
 
44
 
45
+ const field = element.parentNode.querySelector("input");
46
+ if (field != null) field.title = tooltip;
 
 
 
 
 
 
 
 
 
 
47
  }
48
 
 
49
  const tooltipCheckNodes = new Set();
 
50
  let tooltipCheckTimer = null;
51
 
52
  function processTooltipCheckNodes() {
53
+ for (const node of tooltipCheckNodes)
54
  updateTooltip(node);
 
55
  tooltipCheckNodes.clear();
56
  }
57
 
58
  onUiUpdate(function (mutationRecords) {
59
  for (const record of mutationRecords) {
 
 
 
 
 
 
 
 
 
 
60
  for (const node of record.addedNodes) {
61
  if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains("hide")) {
62
  if (!node.title) {
63
+ if (["SPAN", "BUTTON", "P"].includes(node.tagName))
 
 
 
 
 
 
64
  tooltipCheckNodes.add(node);
 
65
  }
66
+ node.querySelectorAll('span, button, p').forEach((n) => tooltipCheckNodes.add(n));
67
  }
68
  }
69
  }
 
73
  }
74
  });
75
 
76
+ onUiLoaded(() => {
77
  for (const comp of window.gradio_config.components) {
78
  if (comp.props.webui_tooltip && comp.props.elem_id) {
79
  const elem = gradioApp().getElementById(comp.props.elem_id);
80
+ if (elem) elem.title = comp.props.webui_tooltip;
 
 
81
  }
82
  }
83
  });
ldm_patched/ldm/modules/attention.py CHANGED
@@ -243,27 +243,25 @@ def attention_sage(q, k, v, heads, mask=None):
243
  return out.reshape(b, -1, heads * dim_head)
244
 
245
 
246
- def attention_flash(q, k, v, heads, mask=None, attn_precision=None, skip_reshape=False, skip_output_reshape=False):
247
  """
248
- Reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.30/comfy/ldm/modules/attention.py#L535
249
- Edited by. Haoming02
250
  """
251
 
252
- if skip_reshape:
253
- b, _, _, dim_head = q.shape
254
- else:
255
- b, _, dim_head = q.shape
256
- dim_head //= heads
257
- q, k, v = map(
258
- lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
259
- (q, k, v),
260
- )
261
 
262
- if mask is not None:
263
- if mask.ndim == 2:
264
- mask = mask.unsqueeze(0)
265
- if mask.ndim == 3:
266
- mask = mask.unsqueeze(1)
 
 
 
 
 
267
 
268
  try:
269
  assert mask is None
@@ -278,9 +276,7 @@ def attention_flash(q, k, v, heads, mask=None, attn_precision=None, skip_reshape
278
  print(f"Error using FlashAttention, fallback to PyTorch sdp attention...\n{e}")
279
  out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
280
 
281
- if not skip_output_reshape:
282
- out = out.transpose(1, 2).reshape(b, -1, heads * dim_head)
283
- return out
284
 
285
 
286
  if model_management.sage_enabled():
 
243
  return out.reshape(b, -1, heads * dim_head)
244
 
245
 
246
+ def attention_flash(q, k, v, heads, mask=None):
247
  """
248
+ Reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.49/comfy/ldm/modules/attention.py#L538
249
+ Simplified by. Haoming02
250
  """
251
 
252
+ b, _, dim_head = q.shape
253
+ dim_head //= heads
 
 
 
 
 
 
 
254
 
255
+ if dim_head not in (64, 96, 128):
256
+ if model_management.xformers_enabled():
257
+ return attention_xformers(q, k, v, heads, mask)
258
+ else:
259
+ return attention_pytorch(q, k, v, heads, mask)
260
+
261
+ q, k, v = map(
262
+ lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
263
+ (q, k, v),
264
+ )
265
 
266
  try:
267
  assert mask is None
 
276
  print(f"Error using FlashAttention, fallback to PyTorch sdp attention...\n{e}")
277
  out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
278
 
279
+ return out.transpose(1, 2).reshape(b, -1, heads * dim_head)
 
 
280
 
281
 
282
  if model_management.sage_enabled():
ldm_patched/ldm/modules/diffusionmodules/model.py CHANGED
@@ -223,6 +223,16 @@ def normal_attention(q, k, v):
223
  return h_
224
 
225
 
 
 
 
 
 
 
 
 
 
 
226
  def xformers_attention(q, k, v):
227
  # compute attention
228
  B, C, H, W = q.shape
@@ -232,7 +242,7 @@ def xformers_attention(q, k, v):
232
  )
233
 
234
  try:
235
- out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None)
236
  out = out.transpose(1, 2).reshape(B, C, H, W)
237
  except NotImplementedError:
238
  out = slice_attention(
 
223
  return h_
224
 
225
 
226
+ def get_xformers_flash_attention_op(q, k, v):
227
+ try:
228
+ flash_attention_op = xformers.ops.MemoryEfficientAttentionFlashAttentionOp
229
+ fw, bw = flash_attention_op
230
+ if fw.supports(xformers.ops.fmha.Inputs(query=q, key=k, value=v, attn_bias=None)):
231
+ return flash_attention_op
232
+ except Exception:
233
+ return None
234
+
235
+
236
  def xformers_attention(q, k, v):
237
  # compute attention
238
  B, C, H, W = q.shape
 
242
  )
243
 
244
  try:
245
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=get_xformers_flash_attention_op(q, k, v))
246
  out = out.transpose(1, 2).reshape(B, C, H, W)
247
  except NotImplementedError:
248
  out = slice_attention(
ldm_patched/modules/controlnet.py CHANGED
@@ -135,8 +135,12 @@ class ControlBase:
135
  self.cond_hint = None
136
  self.strength = 1.0
137
  self.timestep_percent_range = (0.0, 1.0)
 
 
138
  self.global_average_pooling = False
139
  self.timestep_range = None
 
 
140
  self.transformer_options = {}
141
 
142
  if device is None:
 
135
  self.cond_hint = None
136
  self.strength = 1.0
137
  self.timestep_percent_range = (0.0, 1.0)
138
+ self.latent_format = None
139
+ self.vae = None
140
  self.global_average_pooling = False
141
  self.timestep_range = None
142
+ self.compression_ratio = 8
143
+ self.upscale_algorithm = 'nearest-exact'
144
  self.transformer_options = {}
145
 
146
  if device is None:
ldm_patched/modules/model_patcher.py CHANGED
@@ -9,6 +9,7 @@ https://github.com/comfyanonymous/ComfyUI
9
  import copy
10
  import inspect
11
  import logging
 
12
 
13
  import torch
14
 
@@ -28,39 +29,37 @@ if PERSISTENT_PATCHES:
28
 
29
  class PatchStatus:
30
  def __init__(self):
31
- self.current = 0 # the current status of the ModelPatcher
32
- self.updated = 0 # the last time a patch was modified
 
 
 
 
33
 
34
  def require_patch(self) -> bool:
35
- if not PERSISTENT_PATCHES:
36
- return True
37
-
38
- return self.current == 0
39
 
40
  def require_unpatch(self) -> bool:
41
- if not PERSISTENT_PATCHES:
42
- return True
43
-
44
- if not PatchStatus.has_lora():
45
- return True
46
 
47
- return self.current != self.updated
48
 
49
  def patch(self):
50
- if self.updated > 0:
51
- self.current = self.updated
 
52
 
53
- def unpatch(self):
54
- self.current = 0
 
55
 
56
- def update(self):
57
- self.updated += 1
58
 
59
- @staticmethod
60
- def has_lora() -> bool:
61
- from modules.shared import sd_model
62
-
63
- return sd_model.current_lora_hash != str([])
64
 
65
 
66
  class ModelPatcher:
@@ -219,7 +218,7 @@ class ModelPatcher:
219
  current_patches.append((strength_patch, patches[k], strength_model))
220
  self.patches[k] = current_patches
221
 
222
- self.patch_status.update()
223
  return list(p)
224
 
225
  def get_key_patches(self, filter_prefix=None):
@@ -255,7 +254,10 @@ class ModelPatcher:
255
  if not patch_weights:
256
  return self.model
257
 
258
- if self.patches and self.patch_status.require_patch():
 
 
 
259
  model_sd = self.model_state_dict()
260
  for key in self.patches:
261
  if key not in model_sd:
@@ -281,6 +283,7 @@ class ModelPatcher:
281
  del temp_weight
282
 
283
  self.patch_status.patch()
 
284
 
285
  if device_to is not None:
286
  self.model.to(device_to)
@@ -463,8 +466,8 @@ class ModelPatcher:
463
 
464
  return weight
465
 
466
- def unpatch_model(self, device_to=None):
467
- if self.backup and self.patch_status.require_unpatch():
468
  keys = list(self.backup.keys())
469
 
470
  if self.weight_inplace_update:
@@ -475,7 +478,8 @@ class ModelPatcher:
475
  ldm_patched.modules.utils.set_attr(self.model, k, self.backup[k])
476
 
477
  self.backup.clear()
478
- self.patch_status.unpatch()
 
479
 
480
  if device_to is not None:
481
  self.model.to(device_to)
 
9
  import copy
10
  import inspect
11
  import logging
12
+ import time
13
 
14
  import torch
15
 
 
29
 
30
  class PatchStatus:
31
  def __init__(self):
32
+ self.t_apply: float = 0
33
+ """the last `time` a Patch was actually **applied**"""
34
+ self.t_added: float = 0
35
+ """the last `time` a new Patch was **added**"""
36
+ self.l_cache: list[tuple[str, float, float]] = None
37
+ """the Patches that are **currently** applied"""
38
 
39
  def require_patch(self) -> bool:
40
+ """whether a new Patch was added after the last application"""
41
+ return self.t_apply < self.t_added
 
 
42
 
43
  def require_unpatch(self) -> bool:
44
+ """whether the current Patches do not match the target Patches"""
45
+ from modules.shared import cached_lora_hash
 
 
 
46
 
47
+ return self.l_cache != cached_lora_hash
48
 
49
  def patch(self):
50
+ """update the time when Patches are applied"""
51
+ self.t_apply = time.time()
52
+ self.sync()
53
 
54
+ def sync(self):
55
+ """update the current Patches to match the system Patches"""
56
+ from modules.shared import cached_lora_hash
57
 
58
+ self.l_cache = cached_lora_hash
 
59
 
60
+ def on_add_patches(self):
61
+ """signal that a new Patch was added"""
62
+ self.t_added = time.time()
 
 
63
 
64
 
65
  class ModelPatcher:
 
218
  current_patches.append((strength_patch, patches[k], strength_model))
219
  self.patches[k] = current_patches
220
 
221
+ self.patch_status.on_add_patches()
222
  return list(p)
223
 
224
  def get_key_patches(self, filter_prefix=None):
 
254
  if not patch_weights:
255
  return self.model
256
 
257
+ if PERSISTENT_PATCHES and self.patch_status.require_unpatch():
258
+ self.unpatch_model(move=True)
259
+
260
+ if self.patches and ((not PERSISTENT_PATCHES) or self.patch_status.require_patch()):
261
  model_sd = self.model_state_dict()
262
  for key in self.patches:
263
  if key not in model_sd:
 
283
  del temp_weight
284
 
285
  self.patch_status.patch()
286
+ logger.debug("Patch Model")
287
 
288
  if device_to is not None:
289
  self.model.to(device_to)
 
466
 
467
  return weight
468
 
469
+ def unpatch_model(self, device_to=None, *, move: bool = (not PERSISTENT_PATCHES)):
470
+ if self.backup and move:
471
  keys = list(self.backup.keys())
472
 
473
  if self.weight_inplace_update:
 
478
  ldm_patched.modules.utils.set_attr(self.model, k, self.backup[k])
479
 
480
  self.backup.clear()
481
+ self.patch_status.sync()
482
+ logger.debug("Unpatch Model")
483
 
484
  if device_to is not None:
485
  self.model.to(device_to)
ldm_patched/modules/sd.py CHANGED
@@ -90,6 +90,7 @@ class CLIP:
90
  self.cond_stage_model,
91
  load_device=load_device,
92
  offload_device=offload_device,
 
93
  )
94
  self.layer_idx = None
95
 
 
90
  self.cond_stage_model,
91
  load_device=load_device,
92
  offload_device=offload_device,
93
+ weight_inplace_update=opts.extra_networks_patch_inplace,
94
  )
95
  self.layer_idx = None
96
 
modules/esrgan_model.py CHANGED
@@ -59,7 +59,7 @@ class UpscalerESRGAN(Upscaler):
59
  tile_overlap=opts.ESRGAN_tile_overlap,
60
  )
61
 
62
- @lru_cache(maxsize=3, typed=False)
63
  def load_model(self, path: str):
64
  if not path.startswith("http"):
65
  filename = path
 
59
  tile_overlap=opts.ESRGAN_tile_overlap,
60
  )
61
 
62
+ @lru_cache(maxsize=4, typed=False)
63
  def load_model(self, path: str):
64
  if not path.startswith("http"):
65
  filename = path
modules/images.py CHANGED
@@ -346,7 +346,7 @@ def sanitize_filename_part(text, replace_spaces=True):
346
  return text
347
 
348
 
349
- @functools.lru_cache(maxsize=10, typed=False)
350
  def get_scheduler_str(sampler_name: str, scheduler_name: str):
351
  """Returns {Scheduler} if the scheduler is applicable to the sampler"""
352
  if scheduler_name == "Automatic":
@@ -355,7 +355,7 @@ def get_scheduler_str(sampler_name: str, scheduler_name: str):
355
  return scheduler_name.capitalize()
356
 
357
 
358
- @functools.lru_cache(maxsize=10, typed=False)
359
  def get_sampler_scheduler_str(sampler_name: str, scheduler_name: str):
360
  """Returns the '{Sampler} {Scheduler}' if the scheduler is applicable to the sampler"""
361
  return f"{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}"
 
346
  return text
347
 
348
 
349
+ @functools.lru_cache(maxsize=4, typed=False)
350
  def get_scheduler_str(sampler_name: str, scheduler_name: str):
351
  """Returns {Scheduler} if the scheduler is applicable to the sampler"""
352
  if scheduler_name == "Automatic":
 
355
  return scheduler_name.capitalize()
356
 
357
 
358
+ @functools.lru_cache(maxsize=4, typed=False)
359
  def get_sampler_scheduler_str(sampler_name: str, scheduler_name: str):
360
  """Returns the '{Sampler} {Scheduler}' if the scheduler is applicable to the sampler"""
361
  return f"{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}"
modules/processing.py CHANGED
@@ -882,6 +882,7 @@ def process_images_inner(p: StableDiffusionProcessing) -> Processed:
882
 
883
  sd_models.reload_model_weights() # model can be changed for example by refiner
884
 
 
885
  p.sd_model.forge_objects = p.sd_model.forge_objects_original.shallow_copy()
886
  p.prompts = p.all_prompts[n * p.batch_size : (n + 1) * p.batch_size]
887
  p.negative_prompts = p.all_negative_prompts[n * p.batch_size : (n + 1) * p.batch_size]
@@ -901,7 +902,8 @@ def process_images_inner(p: StableDiffusionProcessing) -> Processed:
901
  if not p.disable_extra_networks:
902
  extra_networks.activate(p, p.extra_network_data)
903
 
904
- p.sd_model.forge_objects = p.sd_model.forge_objects_after_applying_lora.shallow_copy()
 
905
 
906
  if p.scripts is not None:
907
  p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
@@ -1287,7 +1289,8 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
1287
 
1288
  x = self.rng.next()
1289
 
1290
- self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
 
1291
  apply_token_merging(self.sd_model, self.get_token_merging_ratio())
1292
 
1293
  if self.scripts is not None:
@@ -1399,7 +1402,8 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
1399
  if self.scripts is not None:
1400
  self.scripts.before_hr(self)
1401
 
1402
- self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
 
1403
  apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True))
1404
 
1405
  if self.scripts is not None:
@@ -1717,7 +1721,8 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
1717
  self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier
1718
  x *= self.initial_noise_multiplier
1719
 
1720
- self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
 
1721
  apply_token_merging(self.sd_model, self.get_token_merging_ratio())
1722
 
1723
  if self.scripts is not None:
 
882
 
883
  sd_models.reload_model_weights() # model can be changed for example by refiner
884
 
885
+ del p.sd_model.forge_objects
886
  p.sd_model.forge_objects = p.sd_model.forge_objects_original.shallow_copy()
887
  p.prompts = p.all_prompts[n * p.batch_size : (n + 1) * p.batch_size]
888
  p.negative_prompts = p.all_negative_prompts[n * p.batch_size : (n + 1) * p.batch_size]
 
902
  if not p.disable_extra_networks:
903
  extra_networks.activate(p, p.extra_network_data)
904
 
905
+ if bool(shared.cached_lora_hash):
906
+ p.sd_model.forge_objects = p.sd_model.forge_objects_after_applying_lora.shallow_copy()
907
 
908
  if p.scripts is not None:
909
  p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
 
1289
 
1290
  x = self.rng.next()
1291
 
1292
+ if bool(shared.cached_lora_hash):
1293
+ self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
1294
  apply_token_merging(self.sd_model, self.get_token_merging_ratio())
1295
 
1296
  if self.scripts is not None:
 
1402
  if self.scripts is not None:
1403
  self.scripts.before_hr(self)
1404
 
1405
+ if bool(shared.cached_lora_hash):
1406
+ self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
1407
  apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True))
1408
 
1409
  if self.scripts is not None:
 
1721
  self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier
1722
  x *= self.initial_noise_multiplier
1723
 
1724
+ if bool(shared.cached_lora_hash):
1725
+ self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
1726
  apply_token_merging(self.sd_model, self.get_token_merging_ratio())
1727
 
1728
  if self.scripts is not None:
modules/sd_models.py CHANGED
@@ -446,6 +446,7 @@ def load_model(checkpoint_info=None, already_loaded_state_dict=None):
446
 
447
  model_data.set_sd_model(sd_model)
448
  model_data.was_loaded_at_least_once = True
 
449
 
450
  # Reload embeddings after model load as they may or may not fit the model
451
  sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True)
 
446
 
447
  model_data.set_sd_model(sd_model)
448
  model_data.was_loaded_at_least_once = True
449
+ shared.cached_lora_hash.clear()
450
 
451
  # Reload embeddings after model load as they may or may not fit the model
452
  sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True)
modules/sd_models_types.py CHANGED
@@ -32,5 +32,11 @@ class WebuiSdModel:
32
  is_sdxl: bool
33
  """True if the model's architecture is SD XL"""
34
 
 
 
 
35
  forge_objects: "ForgeObjects"
36
- """The model patchers used by Forge"""
 
 
 
 
32
  is_sdxl: bool
33
  """True if the model's architecture is SD XL"""
34
 
35
+ forge_objects_original: "ForgeObjects"
36
+ """The model patchers freshly created in `forge_loader`"""
37
+
38
  forge_objects: "ForgeObjects"
39
+ """The model patchers actively used during generation"""
40
+
41
+ forge_objects_after_applying_lora: "ForgeObjects"
42
+ """The model patchers after LoRA is applied; `None` if not using LoRA"""
modules/sd_samplers.py CHANGED
@@ -116,7 +116,7 @@ def get_hr_scheduler_from_infotext(d: dict):
116
  return get_hr_sampler_and_scheduler(d)[1]
117
 
118
 
119
- @functools.lru_cache(maxsize=10, typed=False)
120
  def get_sampler_and_scheduler(sampler_name: str, scheduler_name: str, *, status: bool = False):
121
  default_sampler = samplers[0]
122
  found_scheduler = sd_schedulers.schedulers_map.get(scheduler_name, sd_schedulers.schedulers[0])
 
116
  return get_hr_sampler_and_scheduler(d)[1]
117
 
118
 
119
+ @functools.lru_cache(maxsize=4, typed=False)
120
  def get_sampler_and_scheduler(sampler_name: str, scheduler_name: str, *, status: bool = False):
121
  default_sampler = samplers[0]
122
  found_scheduler = sd_schedulers.schedulers_map.get(scheduler_name, sd_schedulers.schedulers[0])
modules/sd_samplers_common.py CHANGED
@@ -52,7 +52,7 @@ approximation_indexes = {
52
  }
53
 
54
 
55
- @lru_cache(maxsize=(shared.opts.sd_vae_checkpoint_cache), typed=False)
56
  def get_decoder(approximation: int) -> Callable:
57
  match approximation:
58
  case 1:
 
52
  }
53
 
54
 
55
+ @lru_cache(maxsize=getattr(shared.opts, "sd_vae_checkpoint_cache", 1), typed=False)
56
  def get_decoder(approximation: int) -> Callable:
57
  match approximation:
58
  case 1:
modules/shared.py CHANGED
@@ -52,6 +52,7 @@ opts = None
52
  restricted_opts = None
53
 
54
  sd_model: sd_models_types.WebuiSdModel = None
 
55
 
56
  settings_components = None
57
  """assigned from ui.py, a mapping on setting names to gradio components repsponsible for those settings"""
 
52
  restricted_opts = None
53
 
54
  sd_model: sd_models_types.WebuiSdModel = None
55
+ cached_lora_hash: list[tuple[str, float, float]] = [] # persistent patches
56
 
57
  settings_components = None
58
  """assigned from ui.py, a mapping on setting names to gradio components repsponsible for those settings"""
modules/shared_options.py CHANGED
@@ -317,6 +317,7 @@ However, the resulting UI is quite... sluggish.
317
  "extra_networks_add_text_separator": OptionInfo(" ", "Extra Networks Separator").info("additional text to insert before the Extra Networks syntax"),
318
  "ui_extra_networks_tab_reorder": OptionInfo("", "Extra Networks Tab Order").info('tab names separated by "," character; empty = default').needs_reload_ui(),
319
  "textual_inversion_add_hashes_to_infotext": OptionInfo(True, "Append Textual Inversion hashes to infotext"),
 
320
  },
321
  )
322
  )
 
317
  "extra_networks_add_text_separator": OptionInfo(" ", "Extra Networks Separator").info("additional text to insert before the Extra Networks syntax"),
318
  "ui_extra_networks_tab_reorder": OptionInfo("", "Extra Networks Tab Order").info('tab names separated by "," character; empty = default').needs_reload_ui(),
319
  "textual_inversion_add_hashes_to_infotext": OptionInfo(True, "Append Textual Inversion hashes to infotext"),
320
+ "extra_networks_patch_inplace": OptionInfo(False, "Patch the LoRAs in-place").info("reduce peak memory usage").needs_restart(),
321
  },
322
  )
323
  )
modules/ui_extra_networks.py CHANGED
@@ -3,7 +3,6 @@ import json
3
  import os.path
4
  import urllib.parse
5
  from dataclasses import dataclass
6
- from functools import lru_cache
7
  from pathlib import Path
8
  from typing import Optional
9
 
@@ -23,7 +22,6 @@ extra_pages = []
23
  allowed_dirs = set()
24
 
25
 
26
- @lru_cache(maxsize=1, typed=False)
27
  def allowed_preview_extensions():
28
  return ("jpg", "jpeg", "png", "webp")
29
 
 
3
  import os.path
4
  import urllib.parse
5
  from dataclasses import dataclass
 
6
  from pathlib import Path
7
  from typing import Optional
8
 
 
22
  allowed_dirs = set()
23
 
24
 
 
25
  def allowed_preview_extensions():
26
  return ("jpg", "jpeg", "png", "webp")
27
 
modules_forge/diffusion_engine/sgm/models/diffusion.py CHANGED
@@ -4,10 +4,8 @@ from ldm_patched.modules.model_management import unet_dtype, text_encoder_dtype,
4
  from lightning_fabric.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin
5
  from omegaconf import OmegaConf
6
  from modules.shared import opts
7
- from functools import lru_cache
8
 
9
 
10
- @lru_cache(maxsize=1, typed=False)
11
  def _alpha():
12
  from ldm_patched.ldm.modules.diffusionmodules.util import make_beta_schedule
13
  import numpy as np
 
4
  from lightning_fabric.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin
5
  from omegaconf import OmegaConf
6
  from modules.shared import opts
 
7
 
8
 
 
9
  def _alpha():
10
  from ldm_patched.ldm.modules.diffusionmodules.util import make_beta_schedule
11
  import numpy as np
modules_forge/forge_loader.py CHANGED
@@ -35,6 +35,12 @@ class ForgeObjects:
35
  self.vae: VAE = vae
36
  self.clipvision: ModelPatcher = clipvision
37
 
 
 
 
 
 
 
38
  def shallow_copy(self):
39
  return ForgeObjects(self.unet, self.clip, self.vae, self.clipvision)
40
 
@@ -96,6 +102,7 @@ def load_checkpoint_guess_config(sd, output_vae=True, output_clip=True, output_c
96
  load_device=load_device,
97
  offload_device=model_management.unet_offload_device(),
98
  current_device=initial_load_device,
 
99
  )
100
  if initial_load_device != torch.device("cpu"):
101
  print("loaded straight to GPU")
@@ -132,9 +139,9 @@ def load_model_for_a1111(timer, checkpoint_info=None, state_dict=None) -> WebuiS
132
  output_model=True,
133
  )
134
 
135
- sd_model.forge_objects = forge_objects
136
- sd_model.forge_objects_original = forge_objects.shallow_copy()
137
- sd_model.forge_objects_after_applying_lora = forge_objects.shallow_copy()
138
 
139
  del state_dict
140
  timer.record("forge load real models")
@@ -195,8 +202,6 @@ def load_model_for_a1111(timer, checkpoint_info=None, state_dict=None) -> WebuiS
195
  sd_model.sd_model_checkpoint = checkpoint_info.filename
196
  sd_model.sd_checkpoint_info = checkpoint_info
197
 
198
- apply_alpha_schedule_override(sd_model)
199
-
200
  @torch.inference_mode()
201
  def patched_decode_first_stage(x):
202
  sample = sd_model.forge_objects.unet.model.model_config.latent_format.process_out(x)
@@ -240,6 +245,27 @@ def rescale_zero_terminal_snr_abar(alphas_cumprod):
240
  return alphas_bar
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def apply_alpha_schedule_override(sd_model, p=None):
244
  """
245
  Applies an override to the alpha schedule of the model according to settings.
@@ -261,6 +287,7 @@ def apply_alpha_schedule_override(sd_model, p=None):
261
  if p is not None:
262
  p.extra_generation_params["Noise Schedule"] = "Zero Terminal SNR"
263
  sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device)
 
264
 
265
 
266
  ForgeSD = ForgeObjects
 
35
  self.vae: VAE = vae
36
  self.clipvision: ModelPatcher = clipvision
37
 
38
+ def __del__(self):
39
+ del self.unet
40
+ del self.clip
41
+ del self.vae
42
+ del self.clipvision
43
+
44
  def shallow_copy(self):
45
  return ForgeObjects(self.unet, self.clip, self.vae, self.clipvision)
46
 
 
102
  load_device=load_device,
103
  offload_device=model_management.unet_offload_device(),
104
  current_device=initial_load_device,
105
+ weight_inplace_update=shared.opts.extra_networks_patch_inplace,
106
  )
107
  if initial_load_device != torch.device("cpu"):
108
  print("loaded straight to GPU")
 
139
  output_model=True,
140
  )
141
 
142
+ sd_model.forge_objects_original = forge_objects
143
+ sd_model.forge_objects = sd_model.forge_objects_original.shallow_copy()
144
+ sd_model.forge_objects_after_applying_lora = None
145
 
146
  del state_dict
147
  timer.record("forge load real models")
 
202
  sd_model.sd_model_checkpoint = checkpoint_info.filename
203
  sd_model.sd_checkpoint_info = checkpoint_info
204
 
 
 
205
  @torch.inference_mode()
206
  def patched_decode_first_stage(x):
207
  sample = sd_model.forge_objects.unet.model.model_config.latent_format.process_out(x)
 
245
  return alphas_bar
246
 
247
 
248
+ def rescale_zero_terminal_snr_sigmas(sigmas):
249
+ """https://github.com/comfyanonymous/ComfyUI/blob/v0.3.48/comfy/model_sampling.py#L5"""
250
+ alphas_cumprod = 1 / ((sigmas * sigmas) + 1)
251
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
252
+
253
+ # Store old values.
254
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
255
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
256
+
257
+ # Shift so the last timestep is zero.
258
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
259
+
260
+ # Scale so the first timestep is back to the old value.
261
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
262
+
263
+ # Convert alphas_bar_sqrt to betas
264
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
265
+ alphas_bar[-1] = 4.8973451890853435e-08
266
+ return ((1 - alphas_bar) / alphas_bar) ** 0.5
267
+
268
+
269
  def apply_alpha_schedule_override(sd_model, p=None):
270
  """
271
  Applies an override to the alpha schedule of the model according to settings.
 
287
  if p is not None:
288
  p.extra_generation_params["Noise Schedule"] = "Zero Terminal SNR"
289
  sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device)
290
+ sd_model.forge_objects.unet.model.model_sampling.set_sigmas(rescale_zero_terminal_snr_sigmas(sd_model.forge_objects.unet.model.model_sampling.sigmas).to(shared.device))
291
 
292
 
293
  ForgeSD = ForgeObjects