fix: Use runtime monkey patching for reliable CPU offload
Browse files46 unmodified lines4748495051525354555657585960616210 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116255 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512527 unmodified lines26026126226326426526626726846 unmodified linesdef setup_pulid():"""Clone and setup PuLID repository."""pulid_dir = "/tmp/PuLID"# ALWAYS delete and re-clone to ensure patches are applied fresh# This prevents issues with cached/stale code from previous deploymentsif os.path.exists(pulid_dir):import shutilprint("[FLUX-Dev] Removing existing PuLID directory to apply fresh patches...")shutil.rmtree(pulid_dir)if not os.path.exists(pulid_dir):print("[FLUX-Dev] Cloning PuLID repository...")import subprocess10 unmodified linesprint("[FLUX-Dev] Patching app_flux.py to remove gradio dependency...")with open(app_flux_path, "r") as f:content = f.read()# Remove gradio import and related codelines = content.split("\n")patched_lines = []skip_gradio = Falsefor line in lines:# Skip gradio import linesif "import gradio" in line:patched_lines.append("# " + line + " # Removed for API usage")continue# Keep all other linespatched_lines.append(line)with open(app_flux_path, "w") as f:f.write("\n".join(patched_lines))print("[FLUX-Dev] app_flux.py patched successfully")# CRITICAL: Patch flux/util.py to fix device parameter handling# PuLID's load_flow_model() and load_ae() have a bug where they ignore# the device parameter, always loading models to CUDA. This causes OOM# during initialization on GPUs with limited memory.# NOTE: This patch is applied EVERY time (not just on first clone) because# HuggingFace might cache the PuLID directory between deployments.util_path = os.path.join(pulid_dir, "flux", "util.py")if os.path.exists(util_path):with open(util_path, "r") as f:content = f.read()# Check if already patchedif "# PATCHED: respect device param" not in content:print("[FLUX-Dev] Patching flux/util.py to fix device handling...")# Fix load_flow_model: add model.to(device) before returncontent = content.replace(" return model"," model = model.to(device) # PATCHED: respect device param\n return model")# Fix load_ae: add ae.to(device) before returncontent = content.replace(" return ae"," ae = ae.to(device) # PATCHED: respect device param\n return ae")with open(util_path, "w") as f:f.write(content)print("[FLUX-Dev] flux/util.py patched successfully")else:print("[FLUX-Dev] flux/util.py already patched")# CRITICAL: Patch app_flux.py's get_models to load T5/CLIP to CPU when offload=True# Original code always loads T5 and CLIP to GPU regardless of offload flag.app_flux_path = os.path.join(pulid_dir, "app_flux.py")if os.path.exists(app_flux_path):with open(app_flux_path, "r") as f:content = f.read()# Check if get_models is already patchedif "# PATCHED: T5/CLIP offload" not in content:print("[FLUX-Dev] Patching app_flux.py to fix T5/CLIP offload...")# Original: t5 = load_t5(device, max_length=128)# Fixed: t5 = load_t5("cpu" if offload else device, max_length=128)content = content.replace("t5 = load_t5(device, max_length=128)",'t5 = load_t5("cpu" if offload else device, max_length=128) # PATCHED: T5/CLIP offload')# Original: clip = load_clip(device)# Fixed: clip = load_clip("cpu" if offload else device)content = content.replace("clip = load_clip(device)",'clip = load_clip("cpu" if offload else device) # PATCHED: T5/CLIP offload')with open(app_flux_path, "w") as f:f.write(content)print("[FLUX-Dev] app_flux.py patched successfully")else:print("[FLUX-Dev] app_flux.py already patched")# Add to Python pathif pulid_dir not in sys.path:sys.path.insert(0, pulid_dir)return pulid_dir55 unmodified linesprint(f"[FLUX-Dev] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")def _setup_pulid_generator(self):"""Setup PuLID FluxGenerator."""print("[FLUX-Dev] Setting up PuLID generator...")load_start = time.time()self._log_gpu_memory("before_setup_pulid")# Clone and import PuLIDpulid_dir = setup_pulid()self._log_gpu_memory("after_setup_pulid")# Verify patches were appliedutil_path = os.path.join(pulid_dir, "flux", "util.py")app_flux_path = os.path.join(pulid_dir, "app_flux.py")with open(util_path, "r") as f:util_content = f.read()with open(app_flux_path, "r") as f:app_content = f.read()print(f"[FLUX-Dev] util.py patched: {'PATCHED: respect device param' in util_content}")print(f"[FLUX-Dev] app_flux.py patched: {'PATCHED: T5/CLIP offload' in app_content}")# Import PuLID componentsfrom app_flux import FluxGeneratorimport argparseself._log_gpu_memory("after_import")# Create args namespace for FluxGeneratorargs = argparse.Namespace(version=PULID_VERSION,7 unmodified linesdev=False,)print(f"[FLUX-Dev] Initializing FluxGenerator with offload={self.use_offload}, aggressive={self.use_aggressive_offload}")# Initialize generatorself._generator = FluxGenerator(model_name="flux-dev",device="cuda",46 unmodified lines4748495051525354555610 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317455 unmodified lines2302312322332342352362372382392402412422432442452462472482492502517 unmodified lines25926026126226326426526626746 unmodified linesdef setup_pulid():"""Clone and setup PuLID repository with runtime monkey patching."""pulid_dir = "/tmp/PuLID"# Clone if not existsif not os.path.exists(pulid_dir):print("[FLUX-Dev] Cloning PuLID repository...")import subprocess10 unmodified linesprint("[FLUX-Dev] Patching app_flux.py to remove gradio dependency...")with open(app_flux_path, "r") as f:content = f.read()content = content.replace("import gradio as gr", "# import gradio as gr # Removed for API")with open(app_flux_path, "w") as f:f.write(content)print("[FLUX-Dev] app_flux.py patched successfully")# Add to Python path BEFORE importingif pulid_dir not in sys.path:sys.path.insert(0, pulid_dir)# CRITICAL: Apply runtime monkey patches to flux.util module# This is more reliable than source file patching because:# 1. Guaranteed to be applied before any imports# 2. No issues with bytecode caching# 3. Direct function replacementprint("[FLUX-Dev] Applying runtime monkey patches to flux.util...")import flux.util as flux_util# Store original functions_original_load_flow_model = flux_util.load_flow_model_original_load_ae = flux_util.load_ae_original_load_t5 = flux_util.load_t5_original_load_clip = flux_util.load_clipdef patched_load_flow_model(name: str, device: str = "cuda", hf_download: bool = True):"""Patched version that respects device parameter."""print(f"[FLUX-Dev] load_flow_model called with device={device}")model = _original_load_flow_model(name, device=device, hf_download=hf_download)# Force move to specified devicemodel = model.to(device)print(f"[FLUX-Dev] FLUX model loaded to {device}, size={sum(p.numel() for p in model.parameters()) / 1e9:.2f}B params")return modeldef patched_load_ae(name: str, device: str = "cuda", hf_download: bool = True):"""Patched version that respects device parameter."""print(f"[FLUX-Dev] load_ae called with device={device}")ae = _original_load_ae(name, device=device, hf_download=hf_download)# Force move to specified deviceae = ae.to(device)print(f"[FLUX-Dev] AutoEncoder loaded to {device}")return aedef patched_load_t5(device: str = "cuda", max_length: int = 512):"""Patched version that respects device parameter."""print(f"[FLUX-Dev] load_t5 called with device={device}")t5 = _original_load_t5(device=device, max_length=max_length)print(f"[FLUX-Dev] T5 loaded to {device}")return t5def patched_load_clip(device: str = "cuda"):"""Patched version that respects device parameter."""print(f"[FLUX-Dev] load_clip called with device={device}")clip = _original_load_clip(device=device)print(f"[FLUX-Dev] CLIP loaded to {device}")return clip# Apply monkey patches to flux.utilflux_util.load_flow_model = patched_load_flow_modelflux_util.load_ae = patched_load_aeflux_util.load_t5 = patched_load_t5flux_util.load_clip = patched_load_clipprint("[FLUX-Dev] Runtime monkey patches applied to flux.util")# Also patch app_flux.get_models to use CPU for all models when offload=Trueimport app_flux_original_get_models = app_flux.get_modelsdef patched_get_models(name: str, device: torch.device, offload: bool, fp8: bool):"""Patched get_models that loads ALL models to CPU when offload=True."""# When offload is enabled, load ALL models to CPUload_device = "cpu" if offload else str(device)print(f"[FLUX-Dev] patched_get_models: offload={offload}, load_device={load_device}")# Log GPU memory before loadingif torch.cuda.is_available():allocated = torch.cuda.memory_allocated() / 1e9print(f"[FLUX-Dev] GPU memory before get_models: {allocated:.2f}GB")# Use our patched load functionst5 = flux_util.load_t5(load_device, max_length=128)clip = flux_util.load_clip(load_device)if fp8:model = flux_util.load_flow_model_quintized(name, device=load_device)else:model = flux_util.load_flow_model(name, device=load_device)model.eval()ae = flux_util.load_ae(name, device=load_device)# Log GPU memory after loadingif torch.cuda.is_available():allocated = torch.cuda.memory_allocated() / 1e9print(f"[FLUX-Dev] GPU memory after get_models: {allocated:.2f}GB")return model, ae, t5, clipapp_flux.get_models = patched_get_modelsprint("[FLUX-Dev] Runtime monkey patches applied to app_flux.get_models")return pulid_dir55 unmodified linesprint(f"[FLUX-Dev] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")def _setup_pulid_generator(self):"""Setup PuLID FluxGenerator with runtime monkey patching."""print("[FLUX-Dev] Setting up PuLID generator...")load_start = time.time()self._log_gpu_memory("before_setup")# Clone PuLID and apply runtime monkey patches# This patches flux.util functions AND app_flux.get_modelspulid_dir = setup_pulid()self._log_gpu_memory("after_monkey_patch")# Import PuLID components (will use our patched functions)from app_flux import FluxGeneratorimport argparse# Create args namespace for FluxGeneratorargs = argparse.Namespace(version=PULID_VERSION,7 unmodified linesdev=False,)print(f"[FLUX-Dev] Initializing FluxGenerator with offload={self.use_offload}, aggressive={self.use_aggressive_offload}, onnx_provider={args.onnx_provider}")# Initialize generator - will use our patched get_models functionself._generator = FluxGenerator(model_name="flux-dev",device="cuda",
handler.py+103-104