""" Custom Handler for FLUX.1-dev with PuLID using Diffusers Pipeline This handler uses the standard HuggingFace Diffusers FluxPipeline as the base, with PuLID integration for character consistency. This approach provides: 1. Proper memory management via diffusers' enable_model_cpu_offload() 2. Standard diffusers API compatibility 3. More stable operation compared to the original PuLID sampling code Based on: https://github.com/KBRASK/PuLID-FLUX-diffusers API Modes: - register: Register character face -> extract embedding -> cache - generate_with_ids: Generate with cached character embeddings - generate: Normal image generation (no PuLID) - check_cache: Check which character IDs are cached - clear_cache: Clear character embedding cache """ from typing import Dict, List, Any, Union, Optional import torch import torch.nn as nn from io import BytesIO import base64 import time import os import sys import uuid import gc import numpy as np from PIL import Image from types import MethodType # Environment configuration NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28")) PULID_VERSION = os.environ.get("PULID_VERSION", "v0.9.1") def setup_pulid_for_embeddings(): """Clone PuLID repository for ID embedding extraction only.""" pulid_dir = "/tmp/PuLID" if not os.path.exists(pulid_dir): print("[FLUX-Diffusers] Cloning PuLID repository for ID extraction...") import subprocess subprocess.run([ "git", "clone", "--depth", "1", "https://github.com/ToTheBeginning/PuLID.git", pulid_dir ], check=True) print("[FLUX-Diffusers] PuLID cloned successfully") # Patch app_flux.py to remove gradio import 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() content = content.replace("import gradio as gr", "# import gradio as gr") with open(app_flux_path, "w") as f: f.write(content) if pulid_dir not in sys.path: sys.path.insert(0, pulid_dir) return pulid_dir def create_pulid_forward(pulid_ca, double_interval=2, single_interval=4): """Create a patched forward function that injects PuLID ID embeddings. This function wraps the original FluxTransformer2DModel.forward() to inject ID embeddings at regular intervals during the transformer blocks. ID embeddings are read from self._pulid_id_embeddings and self._pulid_id_weight which should be set before calling the pipeline. IMPORTANT: pulid_ca is captured in the closure since it's a nn.ModuleList that needs to be preserved even after enable_model_cpu_offload(). """ # Log closure capture for debugging print(f"[PuLID Forward] Creating patched forward with pulid_ca: {type(pulid_ca)}, len={len(pulid_ca) if pulid_ca else 0}") def forward_with_pulid( self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor = None, pooled_projections: torch.Tensor = None, timestep: torch.LongTensor = None, img_ids: torch.Tensor = None, txt_ids: torch.Tensor = None, guidance: torch.Tensor = None, joint_attention_kwargs: Optional[Dict[str, Any]] = None, controlnet_block_samples=None, controlnet_single_block_samples=None, return_dict: bool = True, controlnet_blocks_repeat: bool = False, ): """Forward with PuLID ID injection.""" from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, scale_lora_layers, unscale_lora_layers from diffusers.models.modeling_outputs import Transformer2DModelOutput # Get PuLID parameters from instance attributes (set before pipeline call) id_embeddings = getattr(self, '_pulid_id_embeddings', None) id_weight = getattr(self, '_pulid_id_weight', 1.0) # Debug: Log PuLID status on first step if not hasattr(self, '_pulid_logged'): self._pulid_logged = True print(f"[PuLID Forward] id_embeddings: {type(id_embeddings)}, shape={id_embeddings.shape if id_embeddings is not None else None}") print(f"[PuLID Forward] id_weight: {id_weight}") print(f"[PuLID Forward] pulid_ca available: {pulid_ca is not None}") ca_idx = 0 if joint_attention_kwargs is not None: joint_attention_kwargs = joint_attention_kwargs.copy() lora_scale = joint_attention_kwargs.pop("scale", 1.0) else: lora_scale = 1.0 if USE_PEFT_BACKEND: scale_lora_layers(self, lora_scale) hidden_states = self.x_embedder(hidden_states) timestep = timestep.to(hidden_states.dtype) * 1000 if guidance is not None: guidance = guidance.to(hidden_states.dtype) * 1000 temb = ( self.time_text_embed(timestep, pooled_projections) if guidance is None else self.time_text_embed(timestep, guidance, pooled_projections) ) encoder_hidden_states = self.context_embedder(encoder_hidden_states) if txt_ids.ndim == 3: txt_ids = txt_ids[0] if img_ids.ndim == 3: img_ids = img_ids[0] ids = torch.cat((txt_ids, img_ids), dim=0) image_rotary_emb = self.pos_embed(ids) # Handle IP adapter if present if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs: ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds") ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds) joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states}) # Double transformer blocks for index_block, block in enumerate(self.transformer_blocks): encoder_hidden_states, hidden_states = block( hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb, image_rotary_emb=image_rotary_emb, joint_attention_kwargs=joint_attention_kwargs, ) # PuLID ID injection for double blocks if pulid_ca is not None and id_embeddings is not None and index_block % double_interval == 0: # Move pulid_ca module to same device as hidden_states if needed ca_module = pulid_ca[ca_idx] if next(ca_module.parameters()).device != hidden_states.device: ca_module = ca_module.to(hidden_states.device) hidden_states = hidden_states + id_weight * ca_module(id_embeddings.to(hidden_states.device), hidden_states) ca_idx += 1 # ControlNet residual if controlnet_block_samples is not None: interval_control = len(self.transformer_blocks) / len(controlnet_block_samples) interval_control = int(np.ceil(interval_control)) if controlnet_blocks_repeat: hidden_states = hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)] else: hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control] hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1) # Single transformer blocks for index_block, block in enumerate(self.single_transformer_blocks): hidden_states = block( hidden_states=hidden_states, temb=temb, image_rotary_emb=image_rotary_emb, joint_attention_kwargs=joint_attention_kwargs, ) # PuLID ID injection for single blocks if pulid_ca is not None and id_embeddings is not None and index_block % single_interval == 0: real_img = hidden_states[:, encoder_hidden_states.shape[1]:, ...] # Move pulid_ca module to same device as hidden_states if needed ca_module = pulid_ca[ca_idx] if next(ca_module.parameters()).device != hidden_states.device: ca_module = ca_module.to(hidden_states.device) real_img = real_img + id_weight * ca_module(id_embeddings.to(hidden_states.device), real_img) hidden_states = torch.cat([ hidden_states[:, :encoder_hidden_states.shape[1], ...], real_img ], dim=1) ca_idx += 1 # ControlNet residual if controlnet_single_block_samples is not None: interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples) interval_control = int(np.ceil(interval_control)) hidden_states[:, encoder_hidden_states.shape[1]:, ...] = ( hidden_states[:, encoder_hidden_states.shape[1]:, ...] + controlnet_single_block_samples[index_block // interval_control] ) hidden_states = hidden_states[:, encoder_hidden_states.shape[1]:, ...] hidden_states = self.norm_out(hidden_states, temb) output = self.proj_out(hidden_states) if USE_PEFT_BACKEND: unscale_lora_layers(self, lora_scale) if not return_dict: return (output,) return Transformer2DModelOutput(sample=output) return forward_with_pulid class EndpointHandler: def __init__(self, path: str = ""): """Initialize FLUX.1-dev pipeline with PuLID support using Diffusers.""" if not torch.cuda.is_available(): raise RuntimeError("GPU is required for FLUX.1-dev inference") self.device = torch.device("cuda") self._pulid_loaded = False # Character embedding cache self.embedding_cache: Dict[str, Dict[str, Any]] = {} # Log GPU info gpu_props = torch.cuda.get_device_properties(0) self.gpu_memory_gb = gpu_props.total_memory / 1e9 print(f"[FLUX-Diffusers] GPU: {gpu_props.name}") print(f"[FLUX-Diffusers] GPU Memory: {self.gpu_memory_gb:.1f} GB") self._setup_pipeline() def _log_gpu_memory(self, stage: str): """Log GPU memory usage.""" if torch.cuda.is_available(): allocated = torch.cuda.memory_allocated() / 1e9 reserved = torch.cuda.memory_reserved() / 1e9 print(f"[FLUX-Diffusers] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB") def _setup_pipeline(self): """Setup diffusers FluxPipeline with PuLID integration.""" print("[FLUX-Diffusers] Setting up pipeline...") load_start = time.time() self._log_gpu_memory("before_setup") # 1. Load base FluxPipeline from diffusers import FluxPipeline print("[FLUX-Diffusers] Loading FluxPipeline...") self.pipe = FluxPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16, ) self._log_gpu_memory("after_flux_load") # 2. Setup PuLID for ID embedding extraction setup_pulid_for_embeddings() from pulid.pipeline_flux import PuLIDPipeline print("[FLUX-Diffusers] Initializing PuLID for ID extraction...") self.pulid_model = PuLIDPipeline( dit=self.pipe.transformer, # Pass transformer to inject pulid_ca device=self.device, weight_dtype=torch.bfloat16, onnx_provider="cpu", # Use CPU for InsightFace to save GPU memory ) self.pulid_model.load_pretrain() self._log_gpu_memory("after_pulid_load") # 3. Store pulid_ca for forward injection # PuLIDPipeline attaches pulid_ca directly to the transformer self.pulid_ca = getattr(self.pipe.transformer, 'pulid_ca', None) print(f"[FLUX-Diffusers] pulid_ca found: {self.pulid_ca is not None}") if self.pulid_ca is not None: print(f"[FLUX-Diffusers] pulid_ca type: {type(self.pulid_ca)}, len: {len(self.pulid_ca)}") # 4. Determine whether to use CPU offload based on GPU memory # H200 (150GB) doesn't need offload, and offload breaks our patched forward use_offload = self.gpu_memory_gb < 80 # Only use offload for smaller GPUs if use_offload: print("[FLUX-Diffusers] GPU < 80GB, enabling CPU offload...") self.pipe.enable_model_cpu_offload() else: print(f"[FLUX-Diffusers] GPU >= 80GB ({self.gpu_memory_gb:.1f}GB), using full GPU mode...") self.pipe.to(self.device) self._log_gpu_memory("after_device_setup") # 5. Patch transformer forward to support ID injection if self.pulid_ca is not None: print("[FLUX-Diffusers] Patching transformer forward for PuLID...") patched_forward = create_pulid_forward(self.pulid_ca) self.pipe.transformer.forward = MethodType(patched_forward, self.pipe.transformer) self._pulid_loaded = True print("[FLUX-Diffusers] PuLID forward patch applied successfully") else: print("[FLUX-Diffusers] Warning: pulid_ca not found, PuLID disabled") self._pulid_loaded = False self._log_gpu_memory("after_patch") # Clean up gc.collect() torch.cuda.empty_cache() print(f"[FLUX-Diffusers] Pipeline ready in {time.time() - load_start:.1f}s") self._log_gpu_memory("final") def _register_character(self, data: Dict) -> Dict: """Register a character face and cache its embedding.""" if not self._pulid_loaded: return {"error": "PuLID not loaded", "success": False} params = data.get("parameters", {}) face_b64 = params.get("face_image", "") char_name = params.get("character_name", "Unknown") if not face_b64: return {"error": "face_image required", "success": False} try: # Decode base64 image if face_b64.startswith("data:"): face_b64 = face_b64.split(",")[1] img_bytes = base64.b64decode(face_b64) img = Image.open(BytesIO(img_bytes)).convert("RGB") img_array = np.array(img) # Resize if needed from pulid.utils import resize_numpy_image_long img_array = resize_numpy_image_long(img_array, 1024) # Extract ID embedding id_embedding, uncond_embedding = self.pulid_model.get_id_embedding( img_array, cal_uncond=True ) # Ensure embeddings are on GPU if id_embedding is not None: id_embedding = id_embedding.to(self.device) if uncond_embedding is not None: uncond_embedding = uncond_embedding.to(self.device) # Generate unique ID and cache char_id = str(uuid.uuid4()) self.embedding_cache[char_id] = { "name": char_name, "id_embedding": id_embedding, "uncond_embedding": uncond_embedding, "created_at": time.time(), } # Check face detection debug_images = self.pulid_model.debug_img_list face_detected = len(debug_images) > 0 print(f"[FLUX-Diffusers] Registered character '{char_name}' with ID {char_id}") return { "success": True, "character_id": char_id, "character_name": char_name, "embedding_cached": True, "face_detected": face_detected, } except Exception as e: print(f"[FLUX-Diffusers] Registration error: {e}") import traceback traceback.print_exc() return {"error": str(e), "success": False} def _generate_with_consistency(self, data: Dict) -> Union[Dict, List[Dict]]: """Generate image(s) with character consistency using cached embeddings.""" if not self._pulid_loaded: return {"error": "PuLID not loaded", "success": False} inputs = data.get("inputs", "") params = data.get("parameters", {}) char_ids = params.get("character_ids", []) # Handle single vs batch inputs single_input = isinstance(inputs, str) prompts = [inputs] if single_input else inputs if not prompts: return {"error": "No prompts provided", "success": False} # Validate character IDs missing_ids = [cid for cid in char_ids if cid not in self.embedding_cache] if missing_ids: return { "error": f"Characters not in cache: {missing_ids}", "success": False, "missing_ids": missing_ids, } if len(char_ids) == 0: return {"error": "At least one character_id required", "success": False} # Get first character's embedding char_data = self.embedding_cache[char_ids[0]] id_embedding = char_data["id_embedding"] # Extract parameters width = params.get("width", 896) height = params.get("height", 1152) num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS) guidance = params.get("guidance_scale", 3.5) id_weight = params.get("id_weight", 1.0) seed = params.get("seed", -1) print(f"[FLUX-Diffusers] Generating {len(prompts)} image(s) with character '{char_data['name']}'") print(f"[FLUX-Diffusers] Settings: id_weight={id_weight}, steps={num_steps}, size={width}x{height}") results = [] for i, prompt in enumerate(prompts): try: print(f"[FLUX-Diffusers] Generating image {i + 1}/{len(prompts)}") self._log_gpu_memory("before_generation") # Set seed generator = None if seed != -1: generator = torch.Generator(device="cpu").manual_seed(seed + i) # Set PuLID parameters on transformer before generation # The patched forward will read these attributes self.pipe.transformer._pulid_id_embeddings = id_embedding self.pipe.transformer._pulid_id_weight = id_weight # Generate with PuLID with torch.inference_mode(): output = self.pipe( prompt=prompt, height=height, width=width, num_inference_steps=num_steps, guidance_scale=guidance, generator=generator, ) # Clear PuLID parameters after generation self.pipe.transformer._pulid_id_embeddings = None self.pipe.transformer._pulid_id_weight = 1.0 image = output.images[0] self._log_gpu_memory("after_generation") # Encode to base64 buffered = BytesIO() image.save(buffered, format="PNG") b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8") results.append({ "success": True, "image": f"data:image/png;base64,{b64_image}", "characters_used": [char_ids[0]], "character_name": char_data["name"], }) # Clean up gc.collect() torch.cuda.empty_cache() except Exception as e: print(f"[FLUX-Diffusers] Generation error: {e}") import traceback traceback.print_exc() results.append({"error": str(e), "success": False}) return results[0] if single_input else results def _generate_normal(self, data: Dict) -> Union[Dict, List[Dict]]: """Normal image generation without character consistency.""" inputs = data.get("inputs", data) params = data.get("parameters", {}) single_input = isinstance(inputs, str) prompts = [inputs] if single_input else inputs # Extract parameters width = params.get("width", 896) height = params.get("height", 1152) num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS) guidance = params.get("guidance_scale", 3.5) seed = params.get("seed", -1) print(f"[FLUX-Diffusers] Generating {len(prompts)} image(s) (no PuLID)") results = [] for i, prompt in enumerate(prompts): try: generator = None if seed != -1: generator = torch.Generator(device="cpu").manual_seed(seed + i) with torch.inference_mode(): output = self.pipe( prompt=prompt, height=height, width=width, num_inference_steps=num_steps, guidance_scale=guidance, generator=generator, ) image = output.images[0] buffered = BytesIO() image.save(buffered, format="PNG") b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8") results.append({ "image": f"data:image/png;base64,{b64_image}" }) gc.collect() torch.cuda.empty_cache() except Exception as e: print(f"[FLUX-Diffusers] Generation error: {e}") results.append({"error": str(e), "success": False}) return results[0] if single_input else results def _check_cache(self, char_ids: List[str]) -> Dict: """Check which character IDs are cached.""" status = {} for cid in char_ids: if cid in self.embedding_cache: status[cid] = { "cached": True, "name": self.embedding_cache[cid]["name"], "created_at": self.embedding_cache[cid]["created_at"], } else: status[cid] = {"cached": False} return { "cache_status": status, "total_cached": len(self.embedding_cache), } def _clear_cache(self, char_ids: Optional[List[str]] = None) -> Dict: """Clear character embedding cache.""" if char_ids: cleared = [] for cid in char_ids: if cid in self.embedding_cache: del self.embedding_cache[cid] cleared.append(cid) return {"cleared": cleared, "remaining": len(self.embedding_cache)} else: count = len(self.embedding_cache) self.embedding_cache.clear() gc.collect() torch.cuda.empty_cache() return {"cleared_all": True, "count": count} def __call__(self, data: Dict[str, Any]) -> Union[Dict, List[Dict]]: """Process image generation request.""" params = data.get("parameters", {}) mode = params.get("mode", "generate") if mode == "register": return self._register_character(data) elif mode == "generate_with_ids": return self._generate_with_consistency(data) elif mode == "check_cache": return self._check_cache(params.get("character_ids", [])) elif mode == "clear_cache": return self._clear_cache(params.get("character_ids")) else: return self._generate_normal(data)