Fix: Use Remote Text Encoding for PyTorch 2.2 compatibility
Browse files12345678916 unmodified lines262728293031323334353637382 unmodified lines41424344454647484950515253545556575859606162636465661 unmodified line6869707172734 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691 unmodified line17117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520622 unmodified lines22923023123223323423514 unmodified lines25025125225325425525625725849 unmodified lines308309310311312313314315316317"""FLUX.2-dev Handler for HuggingFace Dedicated Endpoints (H200)This handler provides high-performance image generation using FLUX.2-dev with:- FP8 quantization via torchao for memory efficiency- torch.compile for optimized inference- Multi-reference image support (up to 10 images)- 1920x1080 output resolution16 unmodified lines}Environment Variables:- HF_TOKEN: HuggingFace token for model access- NUM_INFERENCE_STEPS: Default inference steps (default: 50)- USE_FP8: Enable FP8 quantization (default: true)- USE_COMPILE: Enable torch.compile (default: true)Note: FLUX.2-dev has 32B parameters and requires substantial VRAM.Recommended: H200 (141GB) or H100 (80GB) with FP8 quantization."""from typing import Dict, List, Any, Union, Optional2 unmodified linesimport timeimport base64import osfrom io import BytesIOfrom PIL import Image# Environment configurationNUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "50"))USE_FP8 = os.environ.get("USE_FP8", "true").lower() == "true"USE_COMPILE = os.environ.get("USE_COMPILE", "true").lower() == "true"DEFAULT_WIDTH = 1920DEFAULT_HEIGHT = 1080class EndpointHandler:"""HuggingFace Dedicated Endpoint Handler for FLUX.2-dev."""def __init__(self, path: str = ""):"""Initialize FLUX.2-dev pipeline with optional FP8 quantization."""if not torch.cuda.is_available():raise RuntimeError("GPU is required for FLUX.2-dev inference")self.device = torch.device("cuda")# Log GPU infogpu_props = torch.cuda.get_device_properties(0)1 unmodified lineprint(f"[FLUX2] GPU: {gpu_props.name}")print(f"[FLUX2] GPU Memory: {self.gpu_memory_gb:.1f} GB")print(f"[FLUX2] Compute Capability: {gpu_props.major}.{gpu_props.minor}")self._setup_pipeline()4 unmodified linesreserved = torch.cuda.memory_reserved() / 1e9print(f"[FLUX2] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")def _setup_pipeline(self):"""Setup FLUX.2-dev pipeline with FP8 quantization and torch.compile."""print("[FLUX2] Setting up pipeline...")load_start = time.time()self._log_gpu_memory("before_setup")# Import diffusers components# Note: Actual class names may vary depending on diffusers version# FLUX.2 may use Flux2Pipeline or standard FluxPipeline with different model IDtry:from diffusers import FluxPipeline as Flux2Pipelinefrom diffusers import FluxTransformer2DModel as Flux2Transformer2DModelprint("[FLUX2] Using FluxPipeline (diffusers)")except ImportError:# Fallback if Flux2-specific classes existtry:from diffusers import Flux2Pipeline, Flux2Transformer2DModelprint("[FLUX2] Using Flux2Pipeline (diffusers)")except ImportError:raise RuntimeError("diffusers does not support FLUX.2 yet. Please update diffusers.")# Get HF tokenhf_token = os.environ.get("HF_TOKEN", "")if not hf_token:print("[FLUX2] Warning: HF_TOKEN not set, may fail for gated models")# Model ID - adjust if official FLUX.2 uses different pathmodel_id = "black-forest-labs/FLUX.2-dev"# Check compute capability for FP8 (requires 8.9+)gpu_props = torch.cuda.get_device_properties(0)compute_cap = gpu_props.major + gpu_props.minor / 10use_fp8 = USE_FP8 and compute_cap >= 8.9if USE_FP8 and not use_fp8:print(f"[FLUX2] Warning: FP8 requires compute capability 8.9+, got {compute_cap}")print("[FLUX2] Falling back to BF16")# Load pipeline with FP8 quantization if supportedif use_fp8:print("[FLUX2] Loading with FP8 quantization (torchao)...")try:from diffusers import TorchAoConfigquantization_config = TorchAoConfig("float8dq_e4m3_row")transformer = Flux2Transformer2DModel.from_pretrained(model_id,subfolder="transformer",quantization_config=quantization_config,torch_dtype=torch.bfloat16,token=hf_token if hf_token else None,)print("[FLUX2] Transformer loaded with FP8 quantization")self.pipe = Flux2Pipeline.from_pretrained(model_id,transformer=transformer,torch_dtype=torch.bfloat16,token=hf_token if hf_token else None,)print("[FLUX2] Pipeline created with quantized transformer")except Exception as e:print(f"[FLUX2] FP8 quantization failed: {e}")print("[FLUX2] Falling back to BF16...")self.pipe = Flux2Pipeline.from_pretrained(model_id,torch_dtype=torch.bfloat16,token=hf_token if hf_token else None,)else:print("[FLUX2] Loading without FP8 quantization (BF16)...")self.pipe = Flux2Pipeline.from_pretrained(model_id,torch_dtype=torch.bfloat16,token=hf_token if hf_token else None,)self._log_gpu_memory("after_model_load")# Move to GPU# H200 (141GB) and H100 (80GB) can load full modelif self.gpu_memory_gb >= 70:print("[FLUX2] Loading full model to GPU")self.pipe.to(self.device)else:print("[FLUX2] Using model CPU offload (limited VRAM)")1 unmodified lineself._log_gpu_memory("after_device_setup")# Apply torch.compile for speedupif USE_COMPILE and self.gpu_memory_gb >= 70:print("[FLUX2] Applying torch.compile (mode=reduce-overhead)...")try:self.pipe.transformer = torch.compile(self.pipe.transformer,mode="reduce-overhead",)print("[FLUX2] torch.compile applied successfully")except Exception as e:print(f"[FLUX2] torch.compile failed (continuing without): {e}")self._log_gpu_memory("after_compile")# Warmupprint("[FLUX2] Running warmup...")warmup_start = time.time()try:with torch.inference_mode():_ = self.pipe(prompt="warmup test",num_inference_steps=2,width=512,height=512,guidance_scale=4.0,)warmup_time = time.time() - warmup_startprint(f"[FLUX2] Warmup completed in {warmup_time:.1f}s")except Exception as e:print(f"[FLUX2] Warmup failed: {e}")# Cleanupgc.collect()22 unmodified linesreturn f"data:image/png;base64,{b64_image}"def _generate(self, data: Dict) -> Dict:"""Normal text-to-image generation."""prompt = data.get("inputs", "")params = data.get("parameters", {})14 unmodified linesstart_time = time.time()try:with torch.inference_mode():result = self.pipe(prompt=prompt,width=width,height=height,num_inference_steps=num_steps,49 unmodified linesstart_time = time.time()try:with torch.inference_mode():# FLUX.2 multi-reference: pass images via 'image' parameterresult = self.pipe(prompt=prompt,image=ref_images, # List of PIL Images (up to 10)width=width,height=height,12345678910111216 unmodified lines293031323334353637382 unmodified lines414243444546474849505152535455565758596061626364656667686970711 unmodified line737475767778794 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841 unmodified line18618718818919019119219319419519619719819920020120220320420520622 unmodified lines22923023123223323423514 unmodified lines25025125225325425525625725825926026126249 unmodified lines312313314315316317318319320321322323324325"""FLUX.2-dev Handler for HuggingFace Dedicated EndpointsThis handler uses REMOTE TEXT ENCODING to avoid loading the Mistral3 text encoder locally.This allows running on HuggingFace Inference Endpoints with PyTorch 2.2.0.Features:- Remote text encoding via HuggingFace API (saves ~24GB VRAM)- BF16 precision for transformer- Multi-reference image support (up to 10 images)- 1920x1080 output resolution16 unmodified lines}Environment Variables:- HF_TOKEN: HuggingFace token for model and remote text encoder access (REQUIRED)- NUM_INFERENCE_STEPS: Default inference steps (default: 50)Note: Remote text encoding requires a valid HuggingFace token."""from typing import Dict, List, Any, Union, Optional2 unmodified linesimport timeimport base64import osimport ioimport requestsfrom io import BytesIOfrom PIL import Image# Environment configurationNUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "50"))DEFAULT_WIDTH = 1920DEFAULT_HEIGHT = 1080REMOTE_TEXT_ENCODER_URL = "https://remote-text-encoder-flux-2.huggingface.co/predict"class EndpointHandler:"""HuggingFace Dedicated Endpoint Handler for FLUX.2-dev with Remote Text Encoding."""def __init__(self, path: str = ""):"""Initialize FLUX.2-dev pipeline with remote text encoding."""if not torch.cuda.is_available():raise RuntimeError("GPU is required for FLUX.2-dev inference")self.device = torch.device("cuda")self.hf_token = os.environ.get("HF_TOKEN", "")if not self.hf_token:raise RuntimeError("HF_TOKEN is required for remote text encoding")# Log GPU infogpu_props = torch.cuda.get_device_properties(0)1 unmodified lineprint(f"[FLUX2] GPU: {gpu_props.name}")print(f"[FLUX2] GPU Memory: {self.gpu_memory_gb:.1f} GB")print(f"[FLUX2] Compute Capability: {gpu_props.major}.{gpu_props.minor}")print(f"[FLUX2] Using REMOTE TEXT ENCODING (saves ~24GB VRAM)")self._setup_pipeline()4 unmodified linesreserved = torch.cuda.memory_reserved() / 1e9print(f"[FLUX2] GPU Memory @ {stage}: allocated={allocated:.2f}GB, reserved={reserved:.2f}GB")def _remote_encode_prompt(self, prompt: str) -> torch.Tensor:"""Encode prompt using remote text encoder API."""try:response = requests.post(REMOTE_TEXT_ENCODER_URL,json={"prompt": prompt},headers={"Authorization": f"Bearer {self.hf_token}","Content-Type": "application/json"},timeout=60)if response.status_code != 200:raise RuntimeError(f"Remote text encoder failed: {response.status_code} - {response.text}")# Load the tensor from responseembeddings = torch.load(io.BytesIO(response.content), weights_only=False)return embeddings.to(self.device)except requests.exceptions.RequestException as e:raise RuntimeError(f"Remote text encoder request failed: {e}")def _setup_pipeline(self):"""Setup FLUX.2-dev pipeline with remote text encoding."""print("[FLUX2] Setting up pipeline with remote text encoding...")load_start = time.time()self._log_gpu_memory("before_setup")# Import diffusers componentstry:from diffusers import Flux2Pipeline, Flux2Transformer2DModel, AutoencoderKLFlux2print("[FLUX2] Using Flux2Pipeline (diffusers)")except ImportError:try:from diffusers import FluxPipeline as Flux2Pipelinefrom diffusers import FluxTransformer2DModel as Flux2Transformer2DModelfrom diffusers import AutoencoderKL as AutoencoderKLFlux2print("[FLUX2] Using FluxPipeline fallback (diffusers)")except ImportError:raise RuntimeError("diffusers does not support FLUX.2 yet. Please update diffusers.")model_id = "black-forest-labs/FLUX.2-dev"# Load transformer (main diffusion model)print("[FLUX2] Loading transformer...")self.transformer = Flux2Transformer2DModel.from_pretrained(model_id,subfolder="transformer",torch_dtype=torch.bfloat16,token=self.hf_token,)print("[FLUX2] Transformer loaded")# Load VAEprint("[FLUX2] Loading VAE...")self.vae = AutoencoderKLFlux2.from_pretrained(model_id,subfolder="vae",torch_dtype=torch.bfloat16,token=self.hf_token,)print("[FLUX2] VAE loaded")self._log_gpu_memory("after_model_load")# Load schedulerfrom diffusers import FlowMatchEulerDiscreteSchedulerself.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(model_id,subfolder="scheduler",token=self.hf_token,)# Create pipeline without text encoder (we'll use remote encoding)# Note: We need to handle this differently since Flux2Pipeline expects text encoderself.pipe = Flux2Pipeline.from_pretrained(model_id,transformer=self.transformer,vae=self.vae,text_encoder=None, # Skip text encodertext_encoder_2=None, # Skip second text encoder if anytokenizer=None,tokenizer_2=None,torch_dtype=torch.bfloat16,token=self.hf_token,)# Store reference for remote encodingself.use_remote_encoding = True# Move to GPUif self.gpu_memory_gb >= 40:print("[FLUX2] Loading model to GPU")self.pipe.to(self.device)else:print("[FLUX2] Using model CPU offload (limited VRAM)")1 unmodified lineself._log_gpu_memory("after_device_setup")# Warmup with remote encodingprint("[FLUX2] Running warmup with remote text encoding...")warmup_start = time.time()try:# Test remote text encoderprint("[FLUX2] Testing remote text encoder...")test_embeds = self._remote_encode_prompt("warmup test")print(f"[FLUX2] Remote encoder OK, embedding shape: {test_embeds.shape}")warmup_time = time.time() - warmup_startprint(f"[FLUX2] Warmup completed in {warmup_time:.1f}s")except Exception as e:print(f"[FLUX2] Warmup failed: {e}")import tracebacktraceback.print_exc()# Cleanupgc.collect()22 unmodified linesreturn f"data:image/png;base64,{b64_image}"def _generate(self, data: Dict) -> Dict:"""Normal text-to-image generation with remote text encoding."""prompt = data.get("inputs", "")params = data.get("parameters", {})14 unmodified linesstart_time = time.time()try:# Get text embeddings from remote encoderprint("[FLUX2] Getting text embeddings from remote encoder...")prompt_embeds = self._remote_encode_prompt(prompt)with torch.inference_mode():result = self.pipe(prompt_embeds=prompt_embeds,width=width,height=height,num_inference_steps=num_steps,49 unmodified linesstart_time = time.time()try:# Get text embeddings from remote encoderprint("[FLUX2] Getting text embeddings from remote encoder...")prompt_embeds = self._remote_encode_prompt(prompt)with torch.inference_mode():# FLUX.2 multi-reference: pass images via 'image' parameterresult = self.pipe(prompt_embeds=prompt_embeds,image=ref_images, # List of PIL Images (up to 10)width=width,height=height,
handler.py+116-108