Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,7 @@ import pathlib
|
|
| 9 |
import random
|
| 10 |
import re
|
| 11 |
import shutil
|
|
|
|
| 12 |
import subprocess
|
| 13 |
import sys
|
| 14 |
import traceback
|
|
@@ -61,6 +62,7 @@ if hasattr(torch.cuda, 'get_device_properties'):
|
|
| 61 |
return props
|
| 62 |
torch.cuda.get_device_properties = _patched_get_device_properties
|
| 63 |
|
|
|
|
| 64 |
ROOT = pathlib.Path(__file__).resolve().parent
|
| 65 |
COMFY = ROOT / "ComfyUI"
|
| 66 |
MODELS = COMFY / "models"
|
|
@@ -244,9 +246,9 @@ def _init_comfy_nodes() -> None:
|
|
| 244 |
print("✅ ComfyUI 节点初始化完成!", flush=True)
|
| 245 |
|
| 246 |
|
| 247 |
-
#
|
| 248 |
-
# 🚀 Comfy Speed Patch
|
| 249 |
-
#
|
| 250 |
def patch_comfy_loader():
|
| 251 |
try:
|
| 252 |
comfy_path = str(COMFY.resolve())
|
|
@@ -256,12 +258,16 @@ def patch_comfy_loader():
|
|
| 256 |
import comfy.utils
|
| 257 |
import safetensors.torch
|
| 258 |
import safetensors
|
| 259 |
-
import comfy.ldm.modules.attention
|
| 260 |
-
|
| 261 |
-
|
|
|
|
| 262 |
_original_load_torch_file = comfy.utils.load_torch_file
|
| 263 |
_original_st_load_file = safetensors.torch.load_file
|
| 264 |
|
|
|
|
|
|
|
|
|
|
| 265 |
def _fast_load_torch_file(ckpt, safe_load=False, device=None, return_metadata=False):
|
| 266 |
if device is None:
|
| 267 |
import comfy.model_management
|
|
@@ -274,8 +280,10 @@ def patch_comfy_loader():
|
|
| 274 |
if not file_path.exists():
|
| 275 |
return _original_load_torch_file(ckpt, safe_load, device, return_metadata=return_metadata)
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
| 279 |
try:
|
| 280 |
with open(file_path, "rb") as f:
|
| 281 |
data = f.read()
|
|
@@ -283,14 +291,12 @@ def patch_comfy_loader():
|
|
| 283 |
header_size = int.from_bytes(data[:8], byteorder="little")
|
| 284 |
header = json.loads(data[8:8+header_size].decode("utf-8"))
|
| 285 |
|
| 286 |
-
# 正确提取 header 里的 __metadata__,这是合法的 JSON 字符串字典
|
| 287 |
metadata = header.pop("__metadata__", {})
|
| 288 |
|
| 289 |
tensors = {}
|
| 290 |
data_offset = 8 + header_size
|
| 291 |
|
| 292 |
for tensor_name, info in header.items():
|
| 293 |
-
# 🌟 关键修复:如果权重名恰好叫 metadata,直接跳过,绝不把它当权重读进显存
|
| 294 |
if tensor_name in ("metadata", "__metadata__"):
|
| 295 |
continue
|
| 296 |
|
|
@@ -332,18 +338,82 @@ def patch_comfy_loader():
|
|
| 332 |
safetensors.torch.load_file = _wrapped_st_load_file
|
| 333 |
|
| 334 |
# =========================================================
|
| 335 |
-
#
|
| 336 |
# =========================================================
|
| 337 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
#
|
|
|
|
| 343 |
if metadata_key in state_dict:
|
| 344 |
metadata = state_dict[metadata_key]
|
| 345 |
try:
|
| 346 |
-
# 强行拉回 CPU 转 Numpy 提取 JSON
|
| 347 |
if hasattr(metadata, "cpu"):
|
| 348 |
metadata_cpu = metadata.cpu()
|
| 349 |
if hasattr(metadata_cpu, "numpy"):
|
|
@@ -353,27 +423,21 @@ def patch_comfy_loader():
|
|
| 353 |
elif isinstance(metadata, bytes) or isinstance(metadata, str):
|
| 354 |
self.config = json.loads(metadata)
|
| 355 |
except Exception as e:
|
| 356 |
-
print(f"[🚀 提速补丁] 解析
|
| 357 |
-
|
| 358 |
-
# 处理完立刻删掉,防止底层报 Unexpected key 或者重复处理报错
|
| 359 |
del state_dict[metadata_key]
|
| 360 |
-
|
| 361 |
-
# 如果 local_metadata 里有(有些版本从这里拿),也顺手处理一下
|
| 362 |
-
if local_metadata and isinstance(local_metadata, dict) and "__metadata__" in local_metadata:
|
| 363 |
-
try:
|
| 364 |
-
self.config = json.loads(local_metadata["__metadata__"])
|
| 365 |
-
except:
|
| 366 |
-
pass
|
| 367 |
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
|
| 376 |
-
print("✅ [🚀 提速补丁] V3 部署完成!INT8 Tensor 防御已就绪!", flush=True)
|
| 377 |
except Exception as e:
|
| 378 |
print(f"⚠️ [🚀 提速补丁] 注入失败: {e}", flush=True)
|
| 379 |
|
|
@@ -470,10 +534,43 @@ class UnifiedProgressTqdm(tqdm):
|
|
| 470 |
# ==========================================================================
|
| 471 |
# ⚛️ Comfy Backend & Workflow
|
| 472 |
# ==========================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
def _ref(node: str, output: int = 0) -> list[Any]:
|
| 474 |
return [node, output]
|
| 475 |
|
| 476 |
def _execute_workflow(workflow: dict[str, Any], task_id: str = None) -> list[str]:
|
|
|
|
| 477 |
import tqdm as tqdm_lib
|
| 478 |
import tqdm.auto
|
| 479 |
|
|
@@ -542,7 +639,7 @@ def _execute_workflow(workflow: dict[str, Any], task_id: str = None) -> list[str
|
|
| 542 |
print(f"写入 workflow 指标失败: {e}")
|
| 543 |
|
| 544 |
print(f"[执行器] ✅ ComfyUI Workflow 执行完毕,耗时: {wf_time}s", flush=True)
|
| 545 |
-
|
| 546 |
if not executor.success:
|
| 547 |
message = executor.status_messages[-1] if executor.status_messages else "ComfyUI execution failed"
|
| 548 |
raise RuntimeError(str(message))
|
|
@@ -705,15 +802,17 @@ def generate(
|
|
| 705 |
workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
|
| 706 |
|
| 707 |
# 🌟 策略 C:插入 Comfy Kitchen Attention 后端节点 (使用固定 ID "99" 避开索引冲突)
|
| 708 |
-
|
| 709 |
-
"
|
| 710 |
-
|
| 711 |
-
"
|
| 712 |
-
|
|
|
|
|
|
|
| 713 |
}
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
|
| 718 |
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}}
|
| 719 |
workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
|
|
@@ -752,6 +851,7 @@ class GenerateRequest(BaseModel):
|
|
| 752 |
base_lora_states: list = []
|
| 753 |
|
| 754 |
_model_switch_lock = threading.Lock()
|
|
|
|
| 755 |
|
| 756 |
def background_generate_task(task_id: str, req: GenerateRequest, ip_token: str = None, request: Request = None):
|
| 757 |
global _last_used_architecture, _last_used_unet
|
|
@@ -921,16 +1021,14 @@ async def handle_generate(req: GenerateRequest, background_tasks: BackgroundTask
|
|
| 921 |
ip_token = request.headers.get("x-ip-token")
|
| 922 |
tasks_status[task_id] = {"status": "queued", "message": "⏳ 任务已进入队列..."}
|
| 923 |
|
| 924 |
-
|
|
|
|
|
|
|
|
|
|
| 925 |
import threading
|
| 926 |
-
t = threading.Thread(
|
| 927 |
-
target=background_generate_task,
|
| 928 |
-
args=(task_id, req, ip_token, request),
|
| 929 |
-
daemon=True
|
| 930 |
-
)
|
| 931 |
t.start()
|
| 932 |
|
| 933 |
-
# 瞬间返回,绝不让前端等
|
| 934 |
return {"task_id": task_id, "status": "queued"}
|
| 935 |
|
| 936 |
@app.get("/api/status/{task_id}")
|
|
|
|
| 9 |
import random
|
| 10 |
import re
|
| 11 |
import shutil
|
| 12 |
+
import psutil
|
| 13 |
import subprocess
|
| 14 |
import sys
|
| 15 |
import traceback
|
|
|
|
| 62 |
return props
|
| 63 |
torch.cuda.get_device_properties = _patched_get_device_properties
|
| 64 |
|
| 65 |
+
|
| 66 |
ROOT = pathlib.Path(__file__).resolve().parent
|
| 67 |
COMFY = ROOT / "ComfyUI"
|
| 68 |
MODELS = COMFY / "models"
|
|
|
|
| 246 |
print("✅ ComfyUI 节点初始化完成!", flush=True)
|
| 247 |
|
| 248 |
|
| 249 |
+
# --------------------------------------------------------------------------
|
| 250 |
+
# 🚀 Comfy Speed Patch V7: Brute-Force I/O + Absolute Module Hijack
|
| 251 |
+
# --------------------------------------------------------------------------
|
| 252 |
def patch_comfy_loader():
|
| 253 |
try:
|
| 254 |
comfy_path = str(COMFY.resolve())
|
|
|
|
| 258 |
import comfy.utils
|
| 259 |
import safetensors.torch
|
| 260 |
import safetensors
|
| 261 |
+
import comfy.ldm.modules.attention as attn_module
|
| 262 |
+
import comfy.ops as ops_module
|
| 263 |
+
import inspect
|
| 264 |
+
|
| 265 |
_original_load_torch_file = comfy.utils.load_torch_file
|
| 266 |
_original_st_load_file = safetensors.torch.load_file
|
| 267 |
|
| 268 |
+
# =========================================================
|
| 269 |
+
# 1. 暴力读取 (Brute-Force I/O)
|
| 270 |
+
# =========================================================
|
| 271 |
def _fast_load_torch_file(ckpt, safe_load=False, device=None, return_metadata=False):
|
| 272 |
if device is None:
|
| 273 |
import comfy.model_management
|
|
|
|
| 280 |
if not file_path.exists():
|
| 281 |
return _original_load_torch_file(ckpt, safe_load, device, return_metadata=return_metadata)
|
| 282 |
|
| 283 |
+
file_size_mb = file_path.stat().st_size / (1024 * 1024)
|
| 284 |
+
# 对 500MB 到 20GB 的文件生效
|
| 285 |
+
if file_path.suffix == ".safetensors" and 500 < file_size_mb < 20000:
|
| 286 |
+
print(f"[🚀 提速补丁] 暴力读取大模型: {file_path.name} ({file_size_mb:.1f} MB)", flush=True)
|
| 287 |
try:
|
| 288 |
with open(file_path, "rb") as f:
|
| 289 |
data = f.read()
|
|
|
|
| 291 |
header_size = int.from_bytes(data[:8], byteorder="little")
|
| 292 |
header = json.loads(data[8:8+header_size].decode("utf-8"))
|
| 293 |
|
|
|
|
| 294 |
metadata = header.pop("__metadata__", {})
|
| 295 |
|
| 296 |
tensors = {}
|
| 297 |
data_offset = 8 + header_size
|
| 298 |
|
| 299 |
for tensor_name, info in header.items():
|
|
|
|
| 300 |
if tensor_name in ("metadata", "__metadata__"):
|
| 301 |
continue
|
| 302 |
|
|
|
|
| 338 |
safetensors.torch.load_file = _wrapped_st_load_file
|
| 339 |
|
| 340 |
# =========================================================
|
| 341 |
+
# 2. 通用包装器 (用于替换类方法)
|
| 342 |
# =========================================================
|
| 343 |
+
def _make_patched_load(original_fn, meta_key_name):
|
| 344 |
+
def _patched_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
| 345 |
+
metadata_key = prefix + meta_key_name
|
| 346 |
+
|
| 347 |
+
if metadata_key in state_dict:
|
| 348 |
+
metadata = state_dict[metadata_key]
|
| 349 |
+
try:
|
| 350 |
+
if hasattr(metadata, "cpu"):
|
| 351 |
+
metadata_cpu = metadata.cpu()
|
| 352 |
+
if hasattr(metadata_cpu, "numpy"):
|
| 353 |
+
self.config = json.loads(metadata_cpu.numpy().tobytes())
|
| 354 |
+
else:
|
| 355 |
+
self.config = json.loads(metadata_cpu.tobytes())
|
| 356 |
+
elif isinstance(metadata, bytes) or isinstance(metadata, str):
|
| 357 |
+
self.config = json.loads(metadata)
|
| 358 |
+
except Exception as e:
|
| 359 |
+
print(f"[🚀 提速补丁] 解析 {meta_key_name} config 失败: {e}", flush=True)
|
| 360 |
+
|
| 361 |
+
del state_dict[metadata_key]
|
| 362 |
+
|
| 363 |
+
if local_metadata and isinstance(local_metadata, dict) and "__metadata__" in local_metadata:
|
| 364 |
+
try:
|
| 365 |
+
self.config = json.loads(local_metadata["__metadata__"])
|
| 366 |
+
except:
|
| 367 |
+
pass
|
| 368 |
|
| 369 |
+
return original_fn(
|
| 370 |
+
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 371 |
+
)
|
| 372 |
+
return _patched_load_from_state_dict
|
| 373 |
+
|
| 374 |
+
# =========================================================
|
| 375 |
+
# 3. 清扫 Attention 和 Ops 模块里的类
|
| 376 |
+
# =========================================================
|
| 377 |
+
def _patch_module_classes(module, meta_key_name):
|
| 378 |
+
for class_name, cls in inspect.getmembers(module, inspect.isclass):
|
| 379 |
+
if cls.__module__ != module.__name__:
|
| 380 |
+
continue
|
| 381 |
+
if hasattr(cls, "_load_from_state_dict"):
|
| 382 |
+
_original_fn = getattr(cls, "_load_from_state_dict")
|
| 383 |
+
setattr(cls, "_load_from_state_dict", _make_patched_load(_original_fn, meta_key_name))
|
| 384 |
+
print(f"✅ [🚀 提速补丁] 类方法劫持成功: {module.__name__}.{class_name} (Key: {meta_key_name})", flush=True)
|
| 385 |
+
|
| 386 |
+
_patch_module_classes(attn_module, "metadata")
|
| 387 |
+
_patch_module_classes(ops_module, "layer_conf")
|
| 388 |
+
|
| 389 |
+
# =========================================================
|
| 390 |
+
# 4. 🌟 V7 绝杀:强行重写游离函数 (如果类方法没拦住)
|
| 391 |
+
# =========================================================
|
| 392 |
+
_original_ops_load = getattr(ops_module, "_load_from_state_dict", None)
|
| 393 |
+
|
| 394 |
+
def _fixed_ops_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
| 395 |
+
# 强行剥离 layer_conf
|
| 396 |
+
layer_conf_key = prefix + "layer_conf"
|
| 397 |
+
if layer_conf_key in state_dict:
|
| 398 |
+
layer_conf = state_dict[layer_conf_key]
|
| 399 |
+
try:
|
| 400 |
+
if hasattr(layer_conf, "cpu"):
|
| 401 |
+
layer_conf_cpu = layer_conf.cpu()
|
| 402 |
+
if hasattr(layer_conf_cpu, "numpy"):
|
| 403 |
+
self.config = json.loads(layer_conf_cpu.numpy().tobytes())
|
| 404 |
+
else:
|
| 405 |
+
self.config = json.loads(layer_conf_cpu.tobytes())
|
| 406 |
+
elif isinstance(layer_conf, bytes) or isinstance(layer_conf, str):
|
| 407 |
+
self.config = json.loads(layer_conf)
|
| 408 |
+
except Exception as e:
|
| 409 |
+
print(f"[🚀 提速补丁] V7 解析 layer_conf 失败: {e}", flush=True)
|
| 410 |
+
del state_dict[layer_conf_key]
|
| 411 |
|
| 412 |
+
# 强行剥离 metadata
|
| 413 |
+
metadata_key = prefix + "metadata"
|
| 414 |
if metadata_key in state_dict:
|
| 415 |
metadata = state_dict[metadata_key]
|
| 416 |
try:
|
|
|
|
| 417 |
if hasattr(metadata, "cpu"):
|
| 418 |
metadata_cpu = metadata.cpu()
|
| 419 |
if hasattr(metadata_cpu, "numpy"):
|
|
|
|
| 423 |
elif isinstance(metadata, bytes) or isinstance(metadata, str):
|
| 424 |
self.config = json.loads(metadata)
|
| 425 |
except Exception as e:
|
| 426 |
+
print(f"[🚀 提速补丁] V7 解析 metadata 失败: {e}", flush=True)
|
|
|
|
|
|
|
| 427 |
del state_dict[metadata_key]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
+
if _original_ops_load:
|
| 430 |
+
return _original_ops_load(
|
| 431 |
+
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 432 |
+
)
|
| 433 |
+
else:
|
| 434 |
+
return super(self.__class__, self)._load_from_state_dict(
|
| 435 |
+
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 436 |
+
)
|
| 437 |
|
| 438 |
+
ops_module._load_from_state_dict = _fixed_ops_load_from_state_dict
|
| 439 |
+
print("✅ [🚀 提速补丁] V7 部署完成!comfy.ops 核心加载逻辑已被彻底重写!", flush=True)
|
| 440 |
|
|
|
|
| 441 |
except Exception as e:
|
| 442 |
print(f"⚠️ [🚀 提速补丁] 注入失败: {e}", flush=True)
|
| 443 |
|
|
|
|
| 534 |
# ==========================================================================
|
| 535 |
# ⚛️ Comfy Backend & Workflow
|
| 536 |
# ==========================================================================
|
| 537 |
+
|
| 538 |
+
import psutil
|
| 539 |
+
|
| 540 |
+
def print_ram_status(stage: str):
|
| 541 |
+
mem = psutil.virtual_memory()
|
| 542 |
+
process = psutil.Process(os.getpid())
|
| 543 |
+
proc_mem_gb = process.memory_info().rss / (1024 ** 3)
|
| 544 |
+
total_gb = mem.total / (1024 ** 3)
|
| 545 |
+
avail_gb = mem.available / (1024 ** 3)
|
| 546 |
+
|
| 547 |
+
# 🌟 新增:读取真实的 Cgroup 限制
|
| 548 |
+
cgroup_limit_gb = -1
|
| 549 |
+
try:
|
| 550 |
+
# 尝试读取 Cgroup v2
|
| 551 |
+
with open("/sys/fs/cgroup/memory.max", "r") as f:
|
| 552 |
+
val = f.read().strip()
|
| 553 |
+
if val != "max":
|
| 554 |
+
cgroup_limit_gb = int(val) / (1024 ** 3)
|
| 555 |
+
except FileNotFoundError:
|
| 556 |
+
try:
|
| 557 |
+
# 尝试读取 Cgroup v1
|
| 558 |
+
with open("/sys/fs/cgroup/memory/memory.limit_in_bytes", "r") as f:
|
| 559 |
+
val = f.read().strip()
|
| 560 |
+
# v1 经常用一个巨大的数字表示无限制
|
| 561 |
+
if int(val) < (1 << 60):
|
| 562 |
+
cgroup_limit_gb = int(val) / (1024 ** 3)
|
| 563 |
+
except Exception:
|
| 564 |
+
pass
|
| 565 |
+
|
| 566 |
+
cgroup_str = f" | 容器真实限额: {cgroup_limit_gb:.2f} GB" if cgroup_limit_gb > 0 else " | 容器真实限额: 未知/无限制"
|
| 567 |
+
print(f"[RAM监控 - {stage}] 宿主机总内存: {total_gb:.2f} GB | 宿主机可用: {avail_gb:.2f} GB | 本进程占用: {proc_mem_gb:.2f} GB | 系统已用: {mem.percent}%{cgroup_str}")
|
| 568 |
+
|
| 569 |
def _ref(node: str, output: int = 0) -> list[Any]:
|
| 570 |
return [node, output]
|
| 571 |
|
| 572 |
def _execute_workflow(workflow: dict[str, Any], task_id: str = None) -> list[str]:
|
| 573 |
+
print_ram_status("任务开始前")
|
| 574 |
import tqdm as tqdm_lib
|
| 575 |
import tqdm.auto
|
| 576 |
|
|
|
|
| 639 |
print(f"写入 workflow 指标失败: {e}")
|
| 640 |
|
| 641 |
print(f"[执行器] ✅ ComfyUI Workflow 执行完毕,耗时: {wf_time}s", flush=True)
|
| 642 |
+
print_ram_status("工作流执行完毕后")
|
| 643 |
if not executor.success:
|
| 644 |
message = executor.status_messages[-1] if executor.status_messages else "ComfyUI execution failed"
|
| 645 |
raise RuntimeError(str(message))
|
|
|
|
| 802 |
workflow[str(node_idx+2)] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
|
| 803 |
|
| 804 |
# 🌟 策略 C:插入 Comfy Kitchen Attention 后端节点 (使用固定 ID "99" 避开索引冲突)
|
| 805 |
+
try:
|
| 806 |
+
workflow["99"] = {
|
| 807 |
+
"class_type": "ModelAttentionBackend",
|
| 808 |
+
"inputs": {
|
| 809 |
+
"model": _ref(current_model_node),
|
| 810 |
+
"attention": "comfy kitchen attention"
|
| 811 |
+
}
|
| 812 |
}
|
| 813 |
+
current_model_node = "99"
|
| 814 |
+
except Exception:
|
| 815 |
+
pass # 如果插入失败,current_model_node 依然指向原来的 LoRA 节点
|
| 816 |
|
| 817 |
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}}
|
| 818 |
workflow[str(node_idx+4)] = {"class_type": "VAEDecode", "inputs": {"samples": _ref(str(node_idx+3)), "vae": _ref("3")}}
|
|
|
|
| 851 |
base_lora_states: list = []
|
| 852 |
|
| 853 |
_model_switch_lock = threading.Lock()
|
| 854 |
+
_generation_lock = threading.Lock()
|
| 855 |
|
| 856 |
def background_generate_task(task_id: str, req: GenerateRequest, ip_token: str = None, request: Request = None):
|
| 857 |
global _last_used_architecture, _last_used_unet
|
|
|
|
| 1021 |
ip_token = request.headers.get("x-ip-token")
|
| 1022 |
tasks_status[task_id] = {"status": "queued", "message": "⏳ 任务已进入队列..."}
|
| 1023 |
|
| 1024 |
+
def run_task():
|
| 1025 |
+
with _generation_lock: # 👈 锁住,确保同一时间只有一个任务在跑
|
| 1026 |
+
background_generate_task(task_id, req, ip_token, request)
|
| 1027 |
+
|
| 1028 |
import threading
|
| 1029 |
+
t = threading.Thread(target=run_task, daemon=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1030 |
t.start()
|
| 1031 |
|
|
|
|
| 1032 |
return {"task_id": task_id, "status": "queued"}
|
| 1033 |
|
| 1034 |
@app.get("/api/status/{task_id}")
|