waveshaker commited on
Commit
8a7a643
·
verified ·
1 Parent(s): 43e0002

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -60
app.py CHANGED
@@ -258,8 +258,6 @@ def patch_comfy_loader():
258
  import comfy.utils
259
  import safetensors.torch
260
  import safetensors
261
- import comfy.ldm.modules.attention
262
- from comfy.ldm.modules.attention import OptimizedAttention
263
  print("[🚀 提速补丁] [1/3] ✅ 基础模块导入成功", flush=True)
264
 
265
  _original_load_torch_file = comfy.utils.load_torch_file
@@ -340,7 +338,12 @@ def patch_comfy_loader():
340
  # =========================================================
341
  # 🌟 V3 Core Fix: More aggressive interception of OptimizedAttention._load_from_state_dict
342
  # =========================================================
343
- print("[🚀 提速补丁] [3/3] 正在替换 OptimizedAttention._load_from_state_dict...", flush=True)
 
 
 
 
 
344
  _original_load_from_state_dict = OptimizedAttention._load_from_state_dict
345
 
346
  def _patched_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
@@ -647,6 +650,88 @@ def prepare_env(char_enable: bool, char_lora: str, unet_choice: str, task_id: st
647
  tqdm.auto.tqdm = original_tqdm
648
  _current_download_task_id.set(None)
649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650
  @spaces.GPU(duration=60)
651
  def generate(
652
  prompt: str, unet_choice: str, custom_w: int, custom_h: int,
@@ -705,63 +790,11 @@ def generate(
705
  if lora_cfg["engine"] == engine:
706
  base_lora_inputs.append((lora_cfg["filename"], strength))
707
  try:
708
- current_model_node = "1"
709
- nodes = MODEL_CONFIG["node_types"]
710
- clip_loader_node = engine_cfg.get("clip_loader_override", nodes["clip_loader"])
711
- clip_type = engine_cfg.get("clip_type", "moss_image")
712
- clip_inputs = {"type": clip_type}
713
- te_filenames = engine_cfg.get("local_te_filename", [])
714
- if clip_loader_node == "DualCLIPLoader":
715
- if len(te_filenames) >= 2:
716
- if "clip_l" in te_filenames[0].lower():
717
- clip_inputs["clip_name1"] = te_filenames[0]
718
- clip_inputs["clip_name2"] = te_filenames[1]
719
- else:
720
- clip_inputs["clip_name1"] = te_filenames[1]
721
- clip_inputs["clip_name2"] = te_filenames[0]
722
- elif len(te_filenames) == 1:
723
- clip_inputs["clip_name1"] = te_filenames[0]
724
- else:
725
- if te_filenames: clip_inputs["clip_name"] = te_filenames[0]
726
- if "clip_device" in MODEL_CONFIG.get("loader_args", {}):
727
- clip_inputs["device"] = MODEL_CONFIG["loader_args"]["clip_device"]
728
- vae_filename = engine_cfg.get("local_vae_filename", "")
729
-
730
- workflow = {
731
- "1": {"class_type": nodes["unet_loader"], "inputs": {"unet_name": unet_name, "weight_dtype": "default"}},
732
- "2": {"class_type": clip_loader_node, "inputs": clip_inputs},
733
- "3": {"class_type": nodes["vae_loader"], "inputs": {"vae_name": vae_filename}},
734
- }
735
- node_idx = 4
736
- for lora_file, strength in base_lora_inputs:
737
- # 🌟 策略 B:强制使用 LoraLoaderModelOnly
738
- workflow[str(node_idx)] = {"class_type": "LoraLoaderModelOnly", "inputs": {"model": _ref(current_model_node), "lora_name": lora_file, "strength_model": strength}}
739
- current_model_node = str(node_idx)
740
- node_idx += 1
741
- if char_enable and char_lora:
742
- # 🌟 策略 B:强制使用 LoraLoaderModelOnly,避免全量权重合并带来的巨大延迟
743
- workflow[str(node_idx)] = {"class_type": "LoraLoaderModelOnly", "inputs": {"model": _ref(current_model_node), "lora_name": char_lora, "strength_model": char_strength}}
744
- current_model_node = str(node_idx)
745
- node_idx += 1
746
- final_prompt = prompt.strip()
747
- workflow[str(node_idx)] = {"class_type": "CLIPTextEncode", "inputs": {"clip": _ref("2"), "text": final_prompt}}
748
- workflow[str(node_idx+1)] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": _ref(str(node_idx))}}
749
- workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
750
-
751
- # 🌟 策略 C:插入 Comfy Kitchen Attention 后端节点 (使用固定 ID "99" 避开索引冲突)
752
- workflow["99"] = {
753
- "class_type": "ModelAttentionBackend",
754
- "inputs": {
755
- "model": _ref(current_model_node),
756
- "attention": "comfy kitchen attention"
757
- }
758
- }
759
- # 将 KSampler 的模型引用指向刚插入的 "99" 节点
760
- current_model_node = "99"
761
-
762
- workflow[str(node_idx+3)] = {"class_type": "KSampler", "inputs": {"model": _ref(current_model_node), "positive": _ref(str(node_idx)), "negative": _ref(str(node_idx+1)), "latent_image": _ref(str(node_idx+2)), "seed": effective_seed, "steps": steps, "cfg": cfg, "sampler_name": sampler, "scheduler": scheduler, "denoise": 1.0}}
763
- workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
764
- workflow[str(node_idx+5)] = {"class_type": "SaveImage", "inputs": {"images": _ref(str(node_idx+4)), "filename_prefix": MODEL_CONFIG["name"].lower()}}
765
 
766
  print(f"[GPU 探针] 📦 模型节点构建完毕,准备调用 ComfyUI 执行引擎...", flush=True)
767
  img_path = _execute_workflow(workflow, task_id)[0]
 
258
  import comfy.utils
259
  import safetensors.torch
260
  import safetensors
 
 
261
  print("[🚀 提速补丁] [1/3] ✅ 基础模块导入成功", flush=True)
262
 
263
  _original_load_torch_file = comfy.utils.load_torch_file
 
338
  # =========================================================
339
  # 🌟 V3 Core Fix: More aggressive interception of OptimizedAttention._load_from_state_dict
340
  # =========================================================
341
+ print("[🚀 提速补丁] [3/3] 正在导入并替换 OptimizedAttention...", flush=True)
342
+
343
+ # 👇 核心调整:将这两个 import 挪到 2/3 替换完成之后,确保 1/3 和 2/3 的日志能完整输出
344
+ import comfy.ldm.modules.attention
345
+ from comfy.ldm.modules.attention import OptimizedAttention
346
+
347
  _original_load_from_state_dict = OptimizedAttention._load_from_state_dict
348
 
349
  def _patched_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
 
650
  tqdm.auto.tqdm = original_tqdm
651
  _current_download_task_id.set(None)
652
 
653
+ def build_workflow(
654
+ prompt: str, unet_choice: str, custom_w: int, custom_h: int,
655
+ steps: int, cfg: float, seed: int, sampler: str, scheduler: str,
656
+ char_enable: bool, char_lora: str, char_strength: float,
657
+ lora_states: tuple
658
+ ) -> tuple[dict, str]:
659
+ width, height = int(custom_w), int(custom_h)
660
+ unet_info = UNET_CHOICES[unet_choice]
661
+ unet_name = unet_info["filename"]
662
+ engine = unet_info["engine"]
663
+ engine_cfg = MODEL_CONFIG["models"].get(engine, {})
664
+
665
+ base_lora_inputs = []
666
+ base_choices_list = list(BASE_LORAS_CHOICES.items())
667
+ for i in range(0, len(lora_states), 2):
668
+ enable = lora_states[i]
669
+ strength = float(lora_states[i+1])
670
+ if enable and strength > 0:
671
+ lora_name, lora_cfg = base_choices_list[i // 2]
672
+ if lora_cfg["engine"] == engine:
673
+ base_lora_inputs.append((lora_cfg["filename"], strength))
674
+
675
+ current_model_node = "1"
676
+ nodes = MODEL_CONFIG["node_types"]
677
+ clip_loader_node = engine_cfg.get("clip_loader_override", nodes["clip_loader"])
678
+ clip_type = engine_cfg.get("clip_type", "moss_image")
679
+ clip_inputs = {"type": clip_type}
680
+ te_filenames = engine_cfg.get("local_te_filename", [])
681
+ if clip_loader_node == "DualCLIPLoader":
682
+ if len(te_filenames) >= 2:
683
+ if "clip_l" in te_filenames[0].lower():
684
+ clip_inputs["clip_name1"] = te_filenames[0]
685
+ clip_inputs["clip_name2"] = te_filenames[1]
686
+ else:
687
+ clip_inputs["clip_name1"] = te_filenames[1]
688
+ clip_inputs["clip_name2"] = te_filenames[0]
689
+ elif len(te_filenames) == 1:
690
+ clip_inputs["clip_name1"] = te_filenames[0]
691
+ else:
692
+ if te_filenames: clip_inputs["clip_name"] = te_filenames[0]
693
+ if "clip_device" in MODEL_CONFIG.get("loader_args", {}):
694
+ clip_inputs["device"] = MODEL_CONFIG["loader_args"]["clip_device"]
695
+ vae_filename = engine_cfg.get("local_vae_filename", "")
696
+
697
+ workflow = {
698
+ "1": {"class_type": nodes["unet_loader"], "inputs": {"unet_name": unet_name, "weight_dtype": "default"}},
699
+ "2": {"class_type": clip_loader_node, "inputs": clip_inputs},
700
+ "3": {"class_type": nodes["vae_loader"], "inputs": {"vae_name": vae_filename}},
701
+ }
702
+ node_idx = 4
703
+ for lora_file, strength in base_lora_inputs:
704
+ # 🌟 策略 B:强制使用 LoraLoaderModelOnly
705
+ workflow[str(node_idx)] = {"class_type": "LoraLoaderModelOnly", "inputs": {"model": _ref(current_model_node), "lora_name": lora_file, "strength_model": strength}}
706
+ current_model_node = str(node_idx)
707
+ node_idx += 1
708
+ if char_enable and char_lora:
709
+ # 🌟 策略 B:强制使用 LoraLoaderModelOnly,避免全量权重合并带来的巨大延迟
710
+ workflow[str(node_idx)] = {"class_type": "LoraLoaderModelOnly", "inputs": {"model": _ref(current_model_node), "lora_name": char_lora, "strength_model": char_strength}}
711
+ current_model_node = str(node_idx)
712
+ node_idx += 1
713
+ final_prompt = prompt.strip()
714
+ workflow[str(node_idx)] = {"class_type": "CLIPTextEncode", "inputs": {"clip": _ref("2"), "text": final_prompt}}
715
+ workflow[str(node_idx+1)] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": _ref(str(node_idx))}}
716
+ workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
717
+
718
+ # 🌟 策略 C:插入 Comfy Kitchen Attention 后��节点 (使用固定 ID "99" 避开索引冲突)
719
+ workflow["99"] = {
720
+ "class_type": "ModelAttentionBackend",
721
+ "inputs": {
722
+ "model": _ref(current_model_node),
723
+ "attention": "comfy kitchen attention"
724
+ }
725
+ }
726
+ # 将 KSampler 的模型引用指向刚插入的 "99" 节点
727
+ current_model_node = "99"
728
+
729
+ workflow[str(node_idx+3)] = {"class_type": "KSampler", "inputs": {"model": _ref(current_model_node), "positive": _ref(str(node_idx)), "negative": _ref(str(node_idx+1)), "latent_image": _ref(str(node_idx+2)), "seed": seed, "steps": steps, "cfg": cfg, "sampler_name": sampler, "scheduler": scheduler, "denoise": 1.0}}
730
+ workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
731
+ workflow[str(node_idx+5)] = {"class_type": "SaveImage", "inputs": {"images": _ref(str(node_idx+4)), "filename_prefix": MODEL_CONFIG["name"].lower()}}
732
+
733
+ return workflow, unet_name
734
+
735
  @spaces.GPU(duration=60)
736
  def generate(
737
  prompt: str, unet_choice: str, custom_w: int, custom_h: int,
 
790
  if lora_cfg["engine"] == engine:
791
  base_lora_inputs.append((lora_cfg["filename"], strength))
792
  try:
793
+ workflow, unet_name = build_workflow(
794
+ prompt, unet_choice, custom_w, custom_h,
795
+ steps, cfg, effective_seed, sampler, scheduler,
796
+ char_enable, char_lora, char_strength, lora_states
797
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798
 
799
  print(f"[GPU 探针] 📦 模型节点构建完毕,准备调用 ComfyUI 执行引擎...", flush=True)
800
  img_path = _execute_workflow(workflow, task_id)[0]