Update default resolution to 1536x864
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152164 unmodified lines2212222232242252262272282292302312322332342352362372389 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832841 unmodified line2862872882892902912922932942952962972982 unmodified lines301302303304305306307308309"""Custom Handler for FLUX.1-dev (without PuLID)This handler enables high-quality image generation using FLUX.1-dev modelon Hugging Face Dedicated Endpoints. It provides better quality than schnellwith 28 inference steps (vs 4 for schnell).This is a lightweight version WITHOUT PuLID integration, suitable for:- General image generation without character consistency requirements- Lower memory usage and faster cold starts- Simpler debugging and maintenanceOptimizations applied:- BF16 precision: Optimal for A100/L40S GPU (native Tensor Core support)- torch.compile on Transformer only: CUDA graph optimization (~1.3x speedup)- Fixed batch size padding: Ensures consistent CUDA graph shapes- torch.inference_mode: Reduced memory overheadEnvironment Variables:- TORCH_COMPILE_MODE: "reduce-overhead" (default, fast), "default" (stable), "false" (disabled)- FIXED_BATCH_SIZE: Batch size for CUDA graphs (default: 4)- NUM_INFERENCE_STEPS: Default inference steps (default: 28)GPU Requirements:- A100 80GB: Recommended (full quality, batch processing)- L40S 48GB: Supported with CPU offload- A10G 24GB: Supported with aggressive offloadAPI Format:- Single prompt: {"inputs": "prompt text", "parameters": {...}}- Batch prompts: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}Response Format:- Single: {"image": "base64..."}- Batch: [{"image": "base64..."}, {"image": "base64..."}, ...]References:- FLUX.1-dev: https://huggingface.co/black-forest-labs/FLUX.1-dev"""from typing import Dict, List, Any, Union4 unmodified linesimport osimport gc# Environment configurationTORCH_COMPILE_MODE = os.environ.get("TORCH_COMPILE_MODE", "reduce-overhead").lower()ENABLE_TORCH_COMPILE = TORCH_COMPILE_MODE != "false"FIXED_BATCH_SIZE = int(os.environ.get("FIXED_BATCH_SIZE", "4"))NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))ENABLE_OFFLOAD = os.environ.get("ENABLE_OFFLOAD", "auto").lower()class EndpointHandler:def __init__(self, path: str = ""):"""Initialize the FLUX.1-dev pipeline with optimizations.Optimizations:- BF16 precision (native Tensor Core support)- torch.compile with reduce-overhead mode (optional)- CPU offloading for smaller GPUsArgs:path: Path to model weights (provided by Inference Endpoints)"""from diffusers import FluxPipeline# Check for GPUif not torch.cuda.is_available():raise RuntimeError("GPU is required for FLUX.1-dev inference")self.device = torch.device("cuda")self._compiled = False# Log GPU infogpu_props = torch.cuda.get_device_properties(0)self.gpu_memory_gb = gpu_props.total_memory / 1e9print(f"[FLUX-Dev] GPU: {gpu_props.name}")print(f"[FLUX-Dev] GPU Memory: {self.gpu_memory_gb:.1f} GB")print(f"[FLUX-Dev] Compute Capability: {gpu_props.major}.{gpu_props.minor}")print(f"[FLUX-Dev] CUDA Version: {torch.version.cuda}")print(f"[FLUX-Dev] PyTorch Version: {torch.__version__}")# Determine offload mode based on GPU memoryif ENABLE_OFFLOAD == "auto":# A100 80GB (reports ~85GB): no offload needed# L40S 48GB: use model CPU offload# A10G 24GB: use sequential CPU offloadself.use_offload = self.gpu_memory_gb < 60self.use_sequential_offload = self.gpu_memory_gb < 30elif ENABLE_OFFLOAD == "true":self.use_offload = Trueself.use_sequential_offload = self.gpu_memory_gb < 30else:self.use_offload = Falseself.use_sequential_offload = Falseprint(f"[FLUX-Dev] Offload: {self.use_offload}, Sequential: {self.use_sequential_offload}")# Check if path contains a valid diffusers modelif path and os.path.exists(os.path.join(path, "model_index.json")):model_id = pathelse:model_id = "black-forest-labs/FLUX.1-dev"print(f"[FLUX-Dev] Loading model from: {model_id}")load_start = time.time()# Get HuggingFace token for gated model access# HF_TOKEN is automatically set by Inference Endpoints when configured in secretshf_token = os.environ.get("HF_TOKEN")if hf_token:hf_token = hf_token.strip() # Remove any whitespaceprint(f"[FLUX-Dev] Using HF_TOKEN for authentication (length={len(hf_token)}, prefix={hf_token[:4]}...)")else:print("[FLUX-Dev] Warning: HF_TOKEN not set, may fail for gated models")# Verify token has access to the gated model before loadingif hf_token and model_id == "black-forest-labs/FLUX.1-dev":from huggingface_hub import HfApitry:api = HfApi(token=hf_token)model_info = api.model_info(model_id)print(f"[FLUX-Dev] Token verified: Access to {model_id} confirmed (gated={model_info.gated})")except Exception as e:print(f"[FLUX-Dev] Token verification failed: {e}")print("[FLUX-Dev] Please ensure:")print(" 1. HF_TOKEN has 'read' permission")print(" 2. You have accepted the license at https://huggingface.co/black-forest-labs/FLUX.1-dev")raise RuntimeError(f"Cannot access gated model: {e}")# Load pipeline with BF16self.pipe = FluxPipeline.from_pretrained(model_id,torch_dtype=torch.bfloat16,token=hf_token, # Required for gated models like FLUX.1-dev)# Apply offloading based on GPU memoryif self.use_sequential_offload:print("[FLUX-Dev] Using sequential CPU offload (low memory mode)")self.pipe.enable_sequential_cpu_offload()elif self.use_offload:print("[FLUX-Dev] Using model CPU offload")self.pipe.enable_model_cpu_offload()else:print("[FLUX-Dev] Loading full model to GPU")self.pipe.to(self.device)print(f"[FLUX-Dev] Model loaded in {time.time() - load_start:.1f}s")# Optionally apply torch.compileif ENABLE_TORCH_COMPILE and not self.use_sequential_offload:self._apply_torch_compile()self._run_warmup()else:if self.use_sequential_offload:print("[FLUX-Dev] torch.compile disabled (incompatible with sequential offload)")else:print("[FLUX-Dev] torch.compile disabled")self._compiled = False# Clean up memorygc.collect()torch.cuda.empty_cache()allocated = torch.cuda.memory_allocated() / 1e9print(f"[FLUX-Dev] Ready (compiled={self._compiled}, GPU allocated={allocated:.2f}GB)")def _apply_torch_compile(self):"""Apply torch.compile optimization to transformer."""print(f"[FLUX-Dev] Applying torch.compile (mode={TORCH_COMPILE_MODE})...")compile_start = time.time()try:compile_mode = TORCH_COMPILE_MODE if TORCH_COMPILE_MODE in ["default", "reduce-overhead", "max-autotune"] else "reduce-overhead"# Only compile the transformer (main computation)# VAE decoder runs in eager mode for stabilityself.pipe.transformer = torch.compile(self.pipe.transformer,mode=compile_mode,fullgraph=False,)self._compiled = Trueprint(f"[FLUX-Dev] torch.compile applied in {time.time() - compile_start:.1f}s")except Exception as e:print(f"[FLUX-Dev] torch.compile failed: {e}")self._compiled = Falsedef _run_warmup(self):"""Run warmup inference to capture CUDA graphs."""print(f"[FLUX-Dev] Running warmup at 1344x768 (batch_size={FIXED_BATCH_SIZE})...")warmup_start = time.time()try:with torch.inference_mode():warmup_prompts = ["warmup test image"] * FIXED_BATCH_SIZE_ = self.pipe(prompt=warmup_prompts,num_inference_steps=NUM_INFERENCE_STEPS,width=1344,height=768,guidance_scale=3.5,)print(f"[FLUX-Dev] Warmup completed in {time.time() - warmup_start:.1f}s")except Exception as e:print(f"[FLUX-Dev] Warmup failed: {e}")self._compiled = Falseprint("[FLUX-Dev] Falling back to non-compiled mode")def _cleanup_memory(self):"""Clean up GPU memory."""4 unmodified lines"""Process image generation request(s).Args:data: Request body containing:- inputs: Single prompt (str) or list of prompts (List[str])- parameters (optional):- num_inference_steps: Number of denoising steps (default: 28)- guidance_scale: Prompt adherence (default: 3.5)- width: Image width (default: 1344)- height: Image height (default: 768)- seed: Random seed for reproducibility (default: -1, random)Returns:Single dict or list of dicts with base64-encoded images"""# Extract inputsinputs = data.get("inputs", data)9 unmodified lines# Extract parameters with FLUX.1-dev defaultsnum_inference_steps = parameters.get("num_inference_steps", NUM_INFERENCE_STEPS)guidance_scale = parameters.get("guidance_scale", 3.5)width = parameters.get("width", 1344)height = parameters.get("height", 768)seed = parameters.get("seed", -1)print(f"[FLUX-Dev] Processing {len(prompts)} prompt(s)")print(f"[FLUX-Dev] Settings: steps={num_inference_steps}, guidance={guidance_scale}, size={width}x{height}")# Set up generator for reproducibilitygenerator = Noneif seed != -1:generator = torch.Generator(device="cpu").manual_seed(seed)print(f"[FLUX-Dev] Using seed: {seed}")# Process in fixed-size batchesall_images = []batch_size = FIXED_BATCH_SIZE if self._compiled else min(len(prompts), FIXED_BATCH_SIZE)for i in range(0, len(prompts), batch_size):batch_prompts = prompts[i:i + batch_size]actual_count = len(batch_prompts)# Pad batch for CUDA graph compatibility (only when compiled)if self._compiled and actual_count < FIXED_BATCH_SIZE:padding_prompt = batch_prompts[-1]batch_prompts = batch_prompts + [padding_prompt] * (FIXED_BATCH_SIZE - actual_count)print(f"[FLUX-Dev] Batch {i // batch_size + 1}: {actual_count} real + {FIXED_BATCH_SIZE - actual_count} padding")else:print(f"[FLUX-Dev] Batch {i // batch_size + 1}: {actual_count} images")# Generate imageswith torch.inference_mode():result = self.pipe(prompt=batch_prompts,num_inference_steps=num_inference_steps,1 unmodified lineheight=height,guidance_scale=guidance_scale,generator=generator,)all_images.extend(result.images[:actual_count])# Clean up after each batchself._cleanup_memory()# Encode images to base64encoded_results = []for idx, image in enumerate(all_images):buffered = BytesIO()2 unmodified linesencoded_results.append({"image": f"data:image/png;base64,{b64_image}"})print(f"[FLUX-Dev] Encoded image {idx + 1}/{len(all_images)}")# Return dict for single input, list for batchif single_input:return encoded_results[0]return encoded_results1234567891011121314151617181920212223242526272829303132333435363738394041424344454 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782794 unmodified lines2842852862872882892902912922932942952962972982993003013023033043053063079 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693702 unmodified lines373374375376377378379380381382"""Custom Handler for FLUX.1-dev FP8 optimized for H100 GPUThis handler provides high-performance image generation using FLUX.1-dev withFP8 quantization via torchao, optimized for HuggingFace Dedicated Endpoints.Based on Runpod flux-dev-fp8 handler with HuggingFace Endpoint adaptations.H100-Specific Optimizations:- FP8 quantization via TorchAoConfig: ~2.5x speedup vs optimum-quanto- torch.compile: CUDA graph optimization (~20-30% additional speedup)- Full GPU mode: H100 80GB can load full model without offload- Auto batch sizing: Optimal batch size based on GPU VRAM (8-12 for H100)Environment Variables:- HF_TOKEN: HuggingFace token for gated model access (required)- USE_FP8: Enable FP8 quantization (default: "true")- USE_COMPILE: Enable torch.compile (default: "true")- BATCH_SIZE: Override auto-detected batch size (default: "0" = auto)- NUM_INFERENCE_STEPS: Default inference steps (default: "28")GPU Requirements:- H100 80GB: Optimal (FP8 + full GPU + batch 8-12)- H200 141GB: Supported (batch 24-32)- L40S 48GB: Supported (batch 4-6)- A100 80GB: Supported (FP8 disabled - CC 8.0, batch 6-8 BF16)API Format (HuggingFace Standard):- Single: {"inputs": "prompt text", "parameters": {...}}- Batch: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}Response Format (HuggingFace Standard):- Single: {"image": "data:image/png;base64,..."}- Batch: [{"image": "data:image/png;base64,..."}, ...]Performance (H100 80GB with FP8):- ~3-4 seconds per image (vs ~8 seconds without FP8)- Batch 8-12 images in parallelReferences:- FLUX.1-dev: https://huggingface.co/black-forest-labs/FLUX.1-dev- torchao FP8: https://github.com/pytorch/ao"""from typing import Dict, List, Any, Union4 unmodified linesimport osimport gc# Model IDMODEL_ID = "black-forest-labs/FLUX.1-dev"# Environment configurationUSE_FP8 = os.environ.get("USE_FP8", "true").lower() == "true"USE_COMPILE = os.environ.get("USE_COMPILE", "true").lower() == "true"BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "0")) # 0 = auto-detectNUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))def get_optimal_batch_size(gpu_memory_gb: float, use_fp8: bool) -> int:"""Determine optimal batch size based on GPU memory and precision."""if use_fp8:# FP8: ~12GB model + ~4GB per imageif gpu_memory_gb >= 140: # H200return 24elif gpu_memory_gb >= 80: # H100/A100return 8elif gpu_memory_gb >= 48: # L40Sreturn 6else:return 4else:# BF16: ~24GB model + ~8GB per imageif gpu_memory_gb >= 140: # H200return 12elif gpu_memory_gb >= 80: # H100/A100return 4elif gpu_memory_gb >= 48: # L40Sreturn 3else:return 2class EndpointHandler:def __init__(self, path: str = ""):"""Initialize the FLUX.1-dev pipeline with H100 optimizations.Optimizations:- FP8 quantization via TorchAoConfig (for Hopper GPUs with CC >= 8.9)- torch.compile with reduce-overhead mode- Full GPU mode (no offload for H100/H200)- Auto batch sizingArgs:path: Path to model weights (provided by Inference Endpoints)"""from diffusers import FluxPipeline, FluxTransformer2DModel, TorchAoConfigif not torch.cuda.is_available():raise RuntimeError("GPU is required for FLUX.1-dev inference")self.device = torch.device("cuda")gpu_props = torch.cuda.get_device_properties(0)self.gpu_memory_gb = gpu_props.total_memory / 1e9self.compute_capability = gpu_props.major + gpu_props.minor / 10print(f"[FLUX-FP8] GPU: {gpu_props.name}")print(f"[FLUX-FP8] GPU Memory: {self.gpu_memory_gb:.1f} GB")print(f"[FLUX-FP8] Compute Capability: {gpu_props.major}.{gpu_props.minor}")print(f"[FLUX-FP8] CUDA Version: {torch.version.cuda}")print(f"[FLUX-FP8] PyTorch Version: {torch.__version__}")# Check compute capability for FP8 (requires 8.9+)if USE_FP8 and self.compute_capability < 8.9:print(f"[FLUX-FP8] WARNING: FP8 requires CC 8.9+, got {self.compute_capability}")print("[FLUX-FP8] Falling back to BF16")self.use_fp8 = Falseelse:self.use_fp8 = USE_FP8# Determine batch sizeself.batch_size = BATCH_SIZE if BATCH_SIZE > 0 else get_optimal_batch_size(self.gpu_memory_gb, self.use_fp8)print(f"[FLUX-FP8] Batch Size: {self.batch_size} (FP8={self.use_fp8}, compile={USE_COMPILE})")# Check if path contains a valid diffusers modelif path and os.path.exists(os.path.join(path, "model_index.json")):model_id = pathelse:model_id = MODEL_IDprint(f"[FLUX-FP8] Loading model: {model_id}")load_start = time.time()# Get HuggingFace token for gated model accesshf_token = os.environ.get("HF_TOKEN")if hf_token:hf_token = hf_token.strip()print(f"[FLUX-FP8] Using HF_TOKEN for authentication (length={len(hf_token)})")else:raise RuntimeError("HF_TOKEN is required for FLUX.1-dev (gated model)")# Verify token has access to the gated model before loadingif model_id == MODEL_ID:from huggingface_hub import HfApitry:api = HfApi(token=hf_token)model_info = api.model_info(model_id)print(f"[FLUX-FP8] Token verified: Access to {model_id} confirmed (gated={model_info.gated})")except Exception as e:print(f"[FLUX-FP8] Token verification failed: {e}")print("[FLUX-FP8] Please ensure:")print(" 1. HF_TOKEN has 'read' permission")print(f" 2. You have accepted the license at https://huggingface.co/{model_id}")raise RuntimeError(f"Cannot access gated model: {e}")torch_dtype = torch.bfloat16# Load with FP8 quantization using TorchAoConfig (diffusers native)if self.use_fp8 and self.compute_capability >= 8.9:print("[FLUX-FP8] Loading transformer with TorchAoConfig FP8 quantization (float8dq_e4m3_row)...")try:# float8dq_e4m3_row: FP8 dynamic quantization with per-row scaling# This provides best accuracy vs speed tradeoff (~2.5x faster than optimum-quanto)quantization_config = TorchAoConfig("float8dq_e4m3_row")transformer = FluxTransformer2DModel.from_pretrained(model_id,subfolder="transformer",quantization_config=quantization_config,torch_dtype=torch_dtype,token=hf_token,)print("[FLUX-FP8] Transformer loaded with FP8 quantization")self.pipe = FluxPipeline.from_pretrained(model_id,transformer=transformer,torch_dtype=torch_dtype,token=hf_token,)print("[FLUX-FP8] Pipeline created with quantized transformer")except Exception as e:print(f"[FLUX-FP8] FP8 quantization failed: {e}")print("[FLUX-FP8] Falling back to BF16...")self.use_fp8 = Falseself.pipe = FluxPipeline.from_pretrained(model_id,torch_dtype=torch_dtype,token=hf_token,)else:# Load without quantizationprint("[FLUX-FP8] Loading pipeline without FP8 quantization (BF16)...")self.pipe = FluxPipeline.from_pretrained(model_id,torch_dtype=torch_dtype,token=hf_token,)# Enable VAE slicing for memory efficiencyself.pipe.enable_vae_slicing()print("[FLUX-FP8] VAE slicing enabled")# Move to GPU (full GPU mode for H100/H200)# H100 80GB and H200 141GB can load full model without offload# Smaller GPUs need CPU offload (incompatible with torch.compile fullgraph)self.use_compile_actual = USE_COMPILEif self.gpu_memory_gb >= 70: # H100 80GB, H200 141GBprint("[FLUX-FP8] Loading full model to GPU (required for torch.compile)")self.pipe.to(self.device)elif self.gpu_memory_gb >= 40:print("[FLUX-FP8] Using model CPU offload (torch.compile disabled)")self.pipe.enable_model_cpu_offload()self.use_compile_actual = False # Incompatible with CPU offload hookselse:print("[FLUX-FP8] Using sequential CPU offload (torch.compile disabled)")self.pipe.enable_sequential_cpu_offload()self.use_compile_actual = False # Incompatible with CPU offload hooksprint(f"[FLUX-FP8] Model loaded in {time.time() - load_start:.1f}s")# Apply torch.compile for additional speedupself._compiled = Falseif self.use_compile_actual:print("[FLUX-FP8] Applying torch.compile to transformer (mode=reduce-overhead)...")try:self.pipe.transformer = torch.compile(self.pipe.transformer,mode="reduce-overhead",)self._compiled = Trueprint("[FLUX-FP8] torch.compile applied successfully")except Exception as e:print(f"[FLUX-FP8] torch.compile failed (will continue without): {e}")# Note: Warmup is now called separately from main.py as a background task# to allow /health endpoint to respond immediately after model load# Clean up memorygc.collect()torch.cuda.empty_cache()allocated = torch.cuda.memory_allocated() / 1e9print(f"[FLUX-FP8] Ready (compile={self._compiled}, fp8={self.use_fp8}, GPU allocated={allocated:.2f}GB)")def run_warmup(self):"""Run warmup to trigger Triton JIT compilation during initialization.Uses production settings (1536x864, 28 steps) to ensure complete compilation.This matches Runpod implementation for consistent behavior."""print(f"[FLUX-FP8] Running warmup (1 image, 1536x864, {NUM_INFERENCE_STEPS} steps) to trigger Triton compilation...")warmup_start = time.time()try:with torch.no_grad():_ = self.pipe(prompt="warmup",num_inference_steps=NUM_INFERENCE_STEPS,width=1536,height=864,guidance_scale=3.5,)print(f"[FLUX-FP8] Triton compilation completed in {time.time() - warmup_start:.1f}s")except Exception as e:print(f"[FLUX-FP8] Warmup failed: {e}")import tracebacktraceback.print_exc()print("[FLUX-FP8] Will retry compilation on first request")def _cleanup_memory(self):"""Clean up GPU memory."""4 unmodified lines"""Process image generation request(s).HuggingFace Standard Format:- Single: {"inputs": "prompt text", "parameters": {...}}- Batch: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}Args:data: Request body containing:- inputs: Single prompt (str) or list of prompts (List[str])- parameters (optional):- num_inference_steps: Number of denoising steps (default: 28)- guidance_scale: Prompt adherence (default: 3.5)- width: Image width (default: 1536)- height: Image height (default: 864)- seed: Random seed for reproducibility (default: -1, random)Returns:HuggingFace Standard Format:- Single: {"image": "data:image/png;base64,..."}- Batch: [{"image": "data:image/png;base64,..."}, ...]"""# Extract inputsinputs = data.get("inputs", data)9 unmodified lines# Extract parameters with FLUX.1-dev defaultsnum_inference_steps = parameters.get("num_inference_steps", NUM_INFERENCE_STEPS)guidance_scale = parameters.get("guidance_scale", 3.5)width = parameters.get("width", 1536)height = parameters.get("height", 864)seed = parameters.get("seed", -1)print(f"[FLUX-FP8] Processing {len(prompts)} prompt(s)")print(f"[FLUX-FP8] Settings: steps={num_inference_steps}, guidance={guidance_scale}, size={width}x{height}")# Set up generator for reproducibilitygenerator = Noneif seed != -1:generator = torch.Generator(device="cpu").manual_seed(seed)print(f"[FLUX-FP8] Using seed: {seed}")# Process in batchesall_images = []batch_size = self.batch_sizefor i in range(0, len(prompts), batch_size):batch_prompts = prompts[i:i + batch_size]actual_count = len(batch_prompts)# Log prompt lengths for debuggingprompt_lengths = [len(p) for p in batch_prompts]print(f"[FLUX-FP8] Batch {i // batch_size + 1}: {actual_count} images, prompt chars: {prompt_lengths}")batch_start = time.time()# Use inference_mode for best performance with torchaowith torch.no_grad():result = self.pipe(prompt=batch_prompts,num_inference_steps=num_inference_steps,1 unmodified lineheight=height,guidance_scale=guidance_scale,generator=generator,max_sequence_length=512, # T5 max is 512 tokens (diffusers limitation), CLIP is 77)all_images.extend(result.images)batch_time = time.time() - batch_starttime_per_image = batch_time / actual_countprint(f"[FLUX-FP8] Batch {i // batch_size + 1} completed in {batch_time:.1f}s ({time_per_image:.2f}s/image)")# Cleanup after each batchself._cleanup_memory()# Encode images to base64 (HuggingFace standard format)encoded_results = []for idx, image in enumerate(all_images):buffered = BytesIO()2 unmodified linesencoded_results.append({"image": f"data:image/png;base64,{b64_image}"})if (idx + 1) % 10 == 0 or idx == len(all_images) - 1:print(f"[FLUX-FP8] Encoded image {idx + 1}/{len(all_images)}")# Return dict for single input, list for batch (HuggingFace standard)if single_input:return encoded_results[0]return encoded_results
handler.py+228-155