|
| 1 | +"""Keep at most one resident LightX2V runner across ComfyUI node caches. |
| 2 | +
|
| 3 | +ComfyUI can retain loader outputs after a workflow stops using them. Holding a |
| 4 | +runner directly in each output therefore keeps old models on the GPU when the |
| 5 | +next workflow loads another model. Handles remain cacheable, but their runner |
| 6 | +slot can be cleared and rebuilt when that workflow is used again. |
| 7 | +""" |
| 8 | + |
| 9 | +import functools |
| 10 | +import gc |
| 11 | +import logging |
| 12 | +import sys |
| 13 | +import threading |
| 14 | +import weakref |
| 15 | +from contextlib import contextmanager |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | +from ._lightx2v_runner import build_runner |
| 20 | + |
| 21 | +_LOCK = threading.RLock() |
| 22 | +_HANDLES = weakref.WeakValueDictionary() |
| 23 | +_ACTIVE_REQUESTS = 0 |
| 24 | +_RELEASING = False |
| 25 | + |
| 26 | + |
| 27 | +@contextmanager |
| 28 | +def active_lightx2v_request(): |
| 29 | + """Keep ComfyUI's memory hook from evicting a runner during inference.""" |
| 30 | + global _ACTIVE_REQUESTS |
| 31 | + with _LOCK: |
| 32 | + _ACTIVE_REQUESTS += 1 |
| 33 | + try: |
| 34 | + yield |
| 35 | + finally: |
| 36 | + _ACTIVE_REQUESTS -= 1 |
| 37 | + |
| 38 | + |
| 39 | +def dispose_runner(runner): |
| 40 | + """Drop GPU modules even when an upstream callback still references runner.""" |
| 41 | + if runner is None: |
| 42 | + return |
| 43 | + children = getattr(runner, "clip_generators", None) |
| 44 | + if isinstance(children, dict): |
| 45 | + for child in children.values(): |
| 46 | + dispose_runner(child) |
| 47 | + del runner.clip_generators |
| 48 | + # DefaultRunner.__del__ covers most of these, but only runs once *all* |
| 49 | + # external references disappear. SwiftVR's restorer also holds its own |
| 50 | + # transformer and VAE references and is not covered by that destructor. |
| 51 | + for name in ("restorer", "model", "text_encoders", "image_encoder", "vae_encoder", "vae_decoder", "inputs"): |
| 52 | + if name in getattr(runner, "__dict__", {}): |
| 53 | + delattr(runner, name) |
| 54 | + |
| 55 | + |
| 56 | +def _collect_cuda(): |
| 57 | + # LightX2V freezes the GC generation after a successful request. Unfreeze |
| 58 | + # before dropping runners so cycles containing CUDA tensors can be collected. |
| 59 | + gc.unfreeze() |
| 60 | + gc.collect() |
| 61 | + torch.cuda.empty_cache() |
| 62 | + |
| 63 | + |
| 64 | +def release_restoration_runners(keep=None): |
| 65 | + """Drop SwiftVR/SeedVR runners, including cached ComfyUI loader outputs.""" |
| 66 | + with _LOCK: |
| 67 | + gc.unfreeze() |
| 68 | + released_seedvr = False |
| 69 | + released_swiftvr = False |
| 70 | + for handle in list(_HANDLES.values()): |
| 71 | + if handle is not keep: |
| 72 | + runner = handle["runner"] |
| 73 | + released_seedvr |= runner is not None and handle.startup_config.get("model_cls") == "seedvr2" |
| 74 | + released_swiftvr |= runner is not None and handle.startup_config.get("model_cls") == "swiftvr" |
| 75 | + dispose_runner(runner) |
| 76 | + handle["runner"] = None |
| 77 | + del runner |
| 78 | + if released_seedvr: |
| 79 | + # This @lru_cache is keyed by `self`: without clearing it, every |
| 80 | + # SeedVR RoPE instance (and its GPU model graph) remains reachable. |
| 81 | + rope_module = sys.modules.get("lightx2v.models.networks.seedvr.utils.rope") |
| 82 | + if rope_module is not None: |
| 83 | + rope_module.RotaryEmbeddingBase.get_axial_freqs.cache_clear() |
| 84 | + if released_swiftvr: |
| 85 | + attention_module = sys.modules.get("lightx2v.models.networks.swiftvr.attention") |
| 86 | + if attention_module is not None: |
| 87 | + attention_module.WindowLayout.clear() |
| 88 | + _collect_cuda() |
| 89 | + |
| 90 | + |
| 91 | +def _release_modular_runner(): |
| 92 | + from .inference import LightX2VModularInferenceV2 |
| 93 | + |
| 94 | + if LightX2VModularInferenceV2._current_runner is not None: |
| 95 | + LightX2VModularInferenceV2._release_runner() |
| 96 | + |
| 97 | + |
| 98 | +def release_all_runners(): |
| 99 | + """Evict every resident LightX2V model before ComfyUI allocates VRAM.""" |
| 100 | + global _RELEASING |
| 101 | + with _LOCK: |
| 102 | + if _ACTIVE_REQUESTS or _RELEASING: |
| 103 | + return False |
| 104 | + from .inference import LightX2VModularInferenceV2 |
| 105 | + |
| 106 | + if LightX2VModularInferenceV2._current_runner is None and not any(handle["runner"] is not None for handle in _HANDLES.values()): |
| 107 | + return False |
| 108 | + _RELEASING = True |
| 109 | + try: |
| 110 | + logging.info("Releasing resident LightX2V models for ComfyUI memory management") |
| 111 | + _release_modular_runner() |
| 112 | + release_restoration_runners() |
| 113 | + return True |
| 114 | + finally: |
| 115 | + _RELEASING = False |
| 116 | + |
| 117 | + |
| 118 | +def unload_comfyui_models(): |
| 119 | + """Release ComfyUI-owned models before LightX2V constructs a GPU runner.""" |
| 120 | + import comfy.model_management as model_management |
| 121 | + |
| 122 | + model_management.unload_all_models() |
| 123 | + model_management.soft_empty_cache() |
| 124 | + |
| 125 | + |
| 126 | +def install_comfyui_memory_hook(): |
| 127 | + """Evict LightX2V when ComfyUI's native model manager frees GPU memory. |
| 128 | +
|
| 129 | + Native loads call free_memory through the model_management module, so this |
| 130 | + also covers call sites holding an early-bound reference to load_models_gpu. |
| 131 | + """ |
| 132 | + import comfy.model_management as model_management |
| 133 | + |
| 134 | + original = model_management.free_memory |
| 135 | + if getattr(original, "_lightx2v_memory_hook", False) is True: |
| 136 | + return |
| 137 | + |
| 138 | + @functools.wraps(original) |
| 139 | + def free_memory_with_lightx2v(*args, **kwargs): |
| 140 | + device = args[1] if len(args) > 1 else kwargs.get("device") |
| 141 | + if device is None or getattr(device, "type", None) != "cpu": |
| 142 | + release_all_runners() |
| 143 | + return original(*args, **kwargs) |
| 144 | + |
| 145 | + free_memory_with_lightx2v._lightx2v_memory_hook = True |
| 146 | + model_management.free_memory = free_memory_with_lightx2v |
| 147 | + |
| 148 | + |
| 149 | +def make_runner_handle(config, **metadata): |
| 150 | + """Build a runner after releasing every other LightX2V model.""" |
| 151 | + with _LOCK: |
| 152 | + release_restoration_runners() |
| 153 | + _release_modular_runner() |
| 154 | + unload_comfyui_models() |
| 155 | + runner = build_runner(config) |
| 156 | + handle = RunnerHandle(config, runner, **metadata) |
| 157 | + _HANDLES[id(handle)] = handle |
| 158 | + return handle |
| 159 | + |
| 160 | + |
| 161 | +def get_runner(model): |
| 162 | + """Rebuild an evicted cached loader output before a sampler uses it.""" |
| 163 | + if not isinstance(model, RunnerHandle): |
| 164 | + return model["runner"] |
| 165 | + with _LOCK: |
| 166 | + runner = model["runner"] |
| 167 | + if runner is None: |
| 168 | + release_restoration_runners(keep=model) |
| 169 | + _release_modular_runner() |
| 170 | + unload_comfyui_models() |
| 171 | + runner = build_runner(model.startup_config) |
| 172 | + model["runner"] = runner |
| 173 | + return runner |
| 174 | + |
| 175 | + |
| 176 | +class RunnerHandle(dict): |
| 177 | + """ComfyUI-compatible model output whose GPU state can be evicted.""" |
| 178 | + |
| 179 | + def __init__(self, startup_config, runner, **metadata): |
| 180 | + super().__init__(runner=runner, **metadata) |
| 181 | + self.startup_config = dict(startup_config) |
0 commit comments