Upload handler.py with huggingface_hub
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063072 unmodified lines310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373"""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 resolutionAPI Modes:- generate: Normal text-to-image generation- generate_with_refs: Multi-reference image generation with character/style consistencyInput format:{"inputs": "prompt text","parameters": {"mode": "generate" | "generate_with_refs","reference_images": ["base64...", ...], # For generate_with_refs"width": 1920,"height": 1080,"num_inference_steps": 50,"guidance_scale": 4.0,"seed": -1}}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, Optionalimport torchimport gcimport 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)self.gpu_memory_gb = gpu_props.total_memory / 1e9print(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()def _log_gpu_memory(self, stage: str):"""Log GPU memory usage."""if torch.cuda.is_available():allocated = torch.cuda.memory_allocated() / 1e9reserved = 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)")self.pipe.enable_model_cpu_offload()self._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()torch.cuda.empty_cache()load_time = time.time() - load_startprint(f"[FLUX2] Pipeline ready in {load_time:.1f}s")self._log_gpu_memory("final")def _decode_images(self, images_b64: List[str]) -> List[Image.Image]:"""Decode base64 images to PIL Images."""result = []for b64 in images_b64:if b64.startswith("data:"):b64 = b64.split(",")[1]img_bytes = base64.b64decode(b64)img = Image.open(BytesIO(img_bytes)).convert("RGB")result.append(img)return resultdef _encode_image(self, image: Image.Image) -> str:"""Encode PIL Image to base64 string."""buffered = BytesIO()image.save(buffered, format="PNG")b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")return 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", {})width = params.get("width", DEFAULT_WIDTH)height = params.get("height", DEFAULT_HEIGHT)num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS)guidance = params.get("guidance_scale", 4.0)seed = params.get("seed", -1)print(f"[FLUX2] Generate: steps={num_steps}, size={width}x{height}, guidance={guidance}")# Set up generator for reproducibilitygenerator = Noneif seed != -1:generator = torch.Generator(device="cpu").manual_seed(seed)print(f"[FLUX2] Using seed: {seed}")start_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,guidance_scale=guidance,generator=generator,)generation_time = time.time() - start_timeprint(f"[FLUX2] Generated in {generation_time:.1f}s")# Cleanupgc.collect()torch.cuda.empty_cache()return {"image": self._encode_image(result.images[0]),"generation_time_seconds": generation_time,}except Exception as e:print(f"[FLUX2] Generation error: {e}")import tracebacktraceback.print_exc()return {"error": str(e), "success": False}def _generate_with_refs(self, data: Dict) -> Dict:"""Multi-reference image generation for character/style consistency."""prompt = data.get("inputs", "")params = data.get("parameters", {})ref_images_b64 = params.get("reference_images", [])width = params.get("width", DEFAULT_WIDTH)height = params.get("height", DEFAULT_HEIGHT)num_steps = params.get("num_inference_steps", NUM_INFERENCE_STEPS)# Lower guidance for reference mode (better consistency)guidance = params.get("guidance_scale", 2.5)seed = params.get("seed", -1)# Decode reference imagesref_images = Noneif ref_images_b64:ref_images = self._decode_images(ref_images_b64)print(f"[FLUX2] Using {len(ref_images)} reference image(s)")print(f"[FLUX2] Generate with refs: steps={num_steps}, size={width}x{height}, guidance={guidance}")# Set up generator for reproducibilitygenerator = None2 unmodified linesprint(f"[FLUX2] Using seed: {seed}")start_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,num_inference_steps=num_steps,guidance_scale=guidance,generator=generator,)generation_time = time.time() - start_timeprint(f"[FLUX2] Generated with refs in {generation_time:.1f}s")# Cleanupgc.collect()torch.cuda.empty_cache()return {"image": self._encode_image(result.images[0]),"generation_time_seconds": generation_time,"reference_count": len(ref_images) if ref_images else 0,}except Exception as e:print(f"[FLUX2] Generation error: {e}")import tracebacktraceback.print_exc()return {"error": str(e), "success": False}def __call__(self, data: Dict[str, Any]) -> Union[Dict, List[Dict]]:"""Process image generation request.Args:data: Request data with format:{"inputs": "prompt","parameters": {"mode": "generate" | "generate_with_refs","reference_images": [...], # For generate_with_refs...}}Returns:Dict with generated image(s) or error."""params = data.get("parameters", {})mode = params.get("mode", "generate")if mode == "generate_with_refs":return self._generate_with_refs(data)else:return self._generate(data)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403412 unmodified lines344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451"""FLUX.2-dev FastAPI Handler for HuggingFace Dedicated Endpoints (Custom Container)Features:- FP8 quantization via torchao- torch.compile for optimized inference- TF32 enabled for faster matmul on Ampere+ GPUs- Batch processing (default: 8 images)- Multi-reference image support (up to 10 images)- 1536x864 output resolution (16の倍数、16:9)- Detailed timing logs (inference/encode/gc separate)- Switchable output format (JPEG/PNG)- Semaphore-based request queuing for autoscaling supportAPI Endpoints:- POST /: Generate image(s) (HF Endpoints standard format)- GET /health: Health check- GET /info: Model informationInput format:{"inputs": "prompt text" or ["prompt1", "prompt2", ...],"parameters": {"mode": "generate" | "generate_with_refs","reference_images": ["base64...", ...],"width": 1536,"height": 864,"num_inference_steps": 50,"guidance_scale": 4.0,"seed": -1,"output_format": "jpeg" | "png"}}Environment Variables:- HF_TOKEN: HuggingFace token for model access (REQUIRED)- USE_FP8: Enable FP8 quantization (default: true)- USE_COMPILE: Enable torch.compile (default: true)- NUM_INFERENCE_STEPS: Default inference steps (default: 50)- BATCH_SIZE: Batch size for parallel processing (default: 8)- DEFAULT_OUTPUT_FORMAT: Default output format (default: jpeg)- INFERENCE_TIMEOUT: Max wait time for semaphore in seconds (default: 120)"""import osimport gcimport timeimport base64import asynciofrom io import BytesIOfrom typing import Dict, List, Any, Union, Optionalfrom contextlib import asynccontextmanagerimport torchfrom PIL import Imagefrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Field# ConfigurationHF_TOKEN = os.environ.get("HF_TOKEN", "")USE_FP8 = os.environ.get("USE_FP8", "true").lower() == "true"USE_COMPILE = os.environ.get("USE_COMPILE", "true").lower() == "true"NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "50"))BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "1"))DEFAULT_WIDTH = 1536DEFAULT_HEIGHT = 864 # 16の倍数、16:9DEFAULT_OUTPUT_FORMAT = os.environ.get("DEFAULT_OUTPUT_FORMAT", "jpeg").lower() # jpeg or pngINFERENCE_TIMEOUT = int(os.environ.get("INFERENCE_TIMEOUT", "120")) # Max wait time for semaphore# Global statepipe = Nonemodel_info = {}# Semaphore to limit concurrent GPU inference (1 at a time per instance)# Other requests wait in queue, enabling autoscaling across multiple instancesinference_semaphore = asyncio.Semaphore(1)def load_pipeline():"""Load FLUX.2-dev pipeline with FP8 quantization and torch.compile."""global pipe, model_infoif not torch.cuda.is_available():raise RuntimeError("GPU is required for FLUX.2-dev inference")# Enable TF32 for faster matmul on Ampere+ GPUs (H200, H100, A100)torch.set_float32_matmul_precision("high")torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueprint("[FLUX2] TF32 enabled for matmul operations")device = torch.device("cuda")gpu_props = torch.cuda.get_device_properties(0)gpu_memory_gb = gpu_props.total_memory / 1e9print(f"[FLUX2] GPU: {gpu_props.name}")print(f"[FLUX2] GPU Memory: {gpu_memory_gb:.1f} GB")print(f"[FLUX2] Compute Capability: {gpu_props.major}.{gpu_props.minor}")print(f"[FLUX2] USE_FP8: {USE_FP8}, USE_COMPILE: {USE_COMPILE}")print(f"[FLUX2] BATCH_SIZE: {BATCH_SIZE}")model_id = "black-forest-labs/FLUX.2-dev"load_start = time.time()try:from diffusers import Flux2Pipeline, Flux2Transformer2DModelprint("[FLUX2] Using Flux2Pipeline (diffusers)")except ImportError:try:from diffusers import FluxPipeline as Flux2Pipelinefrom diffusers import FluxTransformer2DModel as Flux2Transformer2DModelprint("[FLUX2] Using FluxPipeline fallback (diffusers)")except ImportError:raise RuntimeError("diffusers does not support FLUX.2 yet")# Load with FP8 quantizationfp8_applied = Falsequantization_type = "none"if USE_FP8:print("[FLUX2] Loading transformer with FP8 quantization...")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,)# Verify FP8 was actually appliedfp8_applied = Truequantization_type = "float8dq_e4m3_row"print("[FLUX2] FP8 quantization applied successfully")print(f"[FLUX2] Config: {quantization_config}")print(f"[FLUX2] Transformer dtype: {transformer.dtype}")pipe = Flux2Pipeline.from_pretrained(model_id,transformer=transformer,torch_dtype=torch.bfloat16,token=HF_TOKEN,)except Exception as e:print(f"[FLUX2] FP8 loading FAILED: {e}")print("[FLUX2] Falling back to BF16 (no quantization)")quantization_type = "bf16_fallback"pipe = Flux2Pipeline.from_pretrained(model_id,torch_dtype=torch.bfloat16,token=HF_TOKEN,)else:print("[FLUX2] Loading without FP8 quantization (disabled by config)")quantization_type = "bf16"pipe = Flux2Pipeline.from_pretrained(model_id,torch_dtype=torch.bfloat16,token=HF_TOKEN,)print(f"[FLUX2] Quantization status: fp8_applied={fp8_applied}, type={quantization_type}")# Move to GPUif gpu_memory_gb >= 40:print("[FLUX2] Loading model to GPU")pipe.to(device)else:print("[FLUX2] Using model CPU offload (limited VRAM)")pipe.enable_model_cpu_offload()# Apply torch.compile to transformerif USE_COMPILE:print("[FLUX2] Applying torch.compile to transformer...")try:pipe.transformer = torch.compile(pipe.transformer,mode="reduce-overhead")print("[FLUX2] torch.compile applied to transformer")except Exception as e:print(f"[FLUX2] torch.compile (transformer) failed: {e}")# Warmup with production size and batch to pre-compile torch.compile cachewarmup_prompts = [f"warmup test {i+1}" for i in range(BATCH_SIZE)]print(f"[FLUX2] Running warmup inference ({DEFAULT_WIDTH}x{DEFAULT_HEIGHT}, batch {BATCH_SIZE})...")warmup_start = time.time()try:with torch.no_grad():_ = pipe(prompt=warmup_prompts,num_inference_steps=2,width=DEFAULT_WIDTH,height=DEFAULT_HEIGHT,)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()torch.cuda.empty_cache()load_time = time.time() - load_startprint(f"[FLUX2] Pipeline ready in {load_time:.1f}s")model_info = {"model_id": model_id,"gpu_name": gpu_props.name,"gpu_memory_gb": gpu_memory_gb,"fp8_applied": fp8_applied,"quantization_type": quantization_type,"use_fp8_config": USE_FP8,"use_compile": USE_COMPILE,"batch_size": BATCH_SIZE,"default_resolution": f"{DEFAULT_WIDTH}x{DEFAULT_HEIGHT}",}# FastAPI app@asynccontextmanagerasync def lifespan(app: FastAPI):"""Load model on startup."""load_pipeline()yieldapp = FastAPI(title="FLUX.2-dev API", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],)class GenerateParameters(BaseModel):mode: str = "generate"reference_images: Optional[List[str]] = Nonewidth: int = Field(default=DEFAULT_WIDTH)height: int = Field(default=DEFAULT_HEIGHT)num_inference_steps: int = Field(default=NUM_INFERENCE_STEPS)guidance_scale: float = Field(default=4.0)seed: int = Field(default=-1)output_format: str = Field(default=DEFAULT_OUTPUT_FORMAT) # jpeg or pngclass GenerateRequest(BaseModel):inputs: Union[str, List[str]]parameters: Optional[GenerateParameters] = Nonedef decode_images(images_b64: List[str]) -> List[Image.Image]:"""Decode base64 images to PIL Images."""result = []for b64 in images_b64:if b64.startswith("data:"):b64 = b64.split(",")[1]img_bytes = base64.b64decode(b64)img = Image.open(BytesIO(img_bytes)).convert("RGB")result.append(img)return resultdef encode_image(image: Image.Image, output_format: str = "jpeg") -> str:"""Encode PIL Image to base64 string."""buffered = BytesIO()if output_format == "png":image.save(buffered, format="PNG")mime_type = "image/png"else:# JPEG (default) - faster encodingif image.mode in ('RGBA', 'LA', 'P'):image = image.convert('RGB')image.save(buffered, format="JPEG", quality=95)mime_type = "image/jpeg"b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")return f"data:{mime_type};base64,{b64_image}"@app.post("/")async def generate(request: GenerateRequest):"""Generate image(s) from prompt(s) (HF Endpoints standard format).Uses semaphore to limit concurrent GPU inference to 1 per instance.Other requests wait in queue (up to INFERENCE_TIMEOUT seconds).This enables autoscaling: HF load balancer distributes requests across instances."""global pipeif pipe is None:raise HTTPException(status_code=503, detail="Model not loaded")# Normalize inputs to listprompts = [request.inputs] if isinstance(request.inputs, str) else request.inputsparams = request.parameters or GenerateParameters()width = params.widthheight = params.heightnum_steps = params.num_inference_stepsguidance = params.guidance_scaleseed = params.seedmode = params.modeoutput_format = params.output_formatref_images_b64 = params.reference_images or []# Wait for semaphore (queue for GPU access)queue_start = time.time()try:await asyncio.wait_for(inference_semaphore.acquire(), timeout=INFERENCE_TIMEOUT)except asyncio.TimeoutError:queue_time = time.time() - queue_startprint(f"[FLUX2] Request timed out after {queue_time:.1f}s waiting for GPU")raise HTTPException(status_code=503, detail=f"Server busy, timed out after {INFERENCE_TIMEOUT}s")queue_time = time.time() - queue_startif queue_time > 1.0:print(f"[FLUX2] Waited {queue_time:.1f}s in queue for GPU access")try:print(f"[FLUX2] Generate: {len(prompts)} prompt(s), mode={mode}, steps={num_steps}, size={width}x{height}, format={output_format}")# Decode reference images if providedref_images = Noneif ref_images_b64:ref_images = decode_images(ref_images_b64)print(f"[FLUX2] Using {len(ref_images)} reference image(s)")# Lower guidance for reference modeif guidance > 2.5:guidance = 2.5print(f"[FLUX2] Guidance scale capped to {guidance} for reference mode")# Set up generator for reproducibilitygenerator = None2 unmodified linesprint(f"[FLUX2] Using seed: {seed}")start_time = time.time()all_images = []total_inference_time = 0.0total_encode_time = 0.0total_gc_time = 0.0# Process in batchesfor i in range(0, len(prompts), BATCH_SIZE):batch_prompts = prompts[i:i + BATCH_SIZE]batch_num = i // BATCH_SIZE + 1total_batches = (len(prompts) + BATCH_SIZE - 1) // BATCH_SIZEprint(f"[FLUX2][BATCH {batch_num}] prompts={len(batch_prompts)}")# Inferenceinference_start = time.time()with torch.no_grad():if ref_images:result = pipe(prompt=batch_prompts,image=ref_images,width=width,height=height,num_inference_steps=num_steps,guidance_scale=guidance,generator=generator,)else:result = pipe(prompt=batch_prompts,width=width,height=height,num_inference_steps=num_steps,guidance_scale=guidance,generator=generator,)inference_time = time.time() - inference_starttotal_inference_time += inference_timeprint(f"[FLUX2][BATCH {batch_num}] inference_time={inference_time:.1f}s ({inference_time/len(batch_prompts):.2f}s/img)")all_images.extend(result.images)# Encode all imagesencode_start = time.time()encoded_images = [encode_image(img, output_format) for img in all_images]encode_time = time.time() - encode_starttotal_encode_time = encode_timeprint(f"[FLUX2][ENCODE] encode_time={encode_time:.1f}s ({encode_time/len(all_images):.2f}s/img) format={output_format}")# Cleanupgc_start = time.time()gc.collect()torch.cuda.empty_cache()gc_time = time.time() - gc_starttotal_gc_time = gc_timeprint(f"[FLUX2][GC] gc_time={gc_time:.2f}s")# Summarytotal_time = time.time() - start_timeprint(f"[FLUX2][SUMMARY] total_images={len(all_images)} total_time={total_time:.1f}s")print(f"[FLUX2][SUMMARY] inference={total_inference_time:.1f}s encode={total_encode_time:.1f}s gc={total_gc_time:.2f}s")print(f"[FLUX2][SUMMARY] avg_per_image={total_time/len(all_images):.2f}s (inference={total_inference_time/len(all_images):.2f}s, encode={total_encode_time/len(all_images):.2f}s)")# Return single image or list based on inputif len(all_images) == 1:return {"image": encoded_images[0],"generation_time_seconds": total_time,"inference_time_seconds": total_inference_time,"encode_time_seconds": total_encode_time,"reference_count": len(ref_images) if ref_images else 0,}else:return {"images": encoded_images,"generation_time_seconds": total_time,"inference_time_seconds": total_inference_time,"encode_time_seconds": total_encode_time,"time_per_image": total_time / len(all_images),"batch_size_used": BATCH_SIZE,"reference_count": len(ref_images) if ref_images else 0,}except Exception as e:print(f"[FLUX2] Generation error: {e}")import tracebacktraceback.print_exc()raise HTTPException(status_code=500, detail=str(e))finally:# Always release semaphore to allow next requestinference_semaphore.release()@app.get("/health")async def health():"""Health check endpoint."""return {"status": "healthy" if pipe is not None else "loading","model_loaded": pipe is not None,"gpu_available": torch.cuda.is_available(),}@app.get("/info")async def info():"""Get model information."""return model_info
handler.py+387-309