Update default resolution to 1536x864
Browse files122345645689101178131415161791011121314152021221617181920212225262723242526272930312829303133343532333435363738394041424344454 unmodified lines5051525354555650515257585960546162636465666768697071727374757677787980818283848586878889609091926364656693949596979899100701011027210310410510677787910710882838485868788899091929394959697109110111112113114115116117118119120121122991001231241021251261271281291301311321331341081351361101371381391401141411421171181431441451201461471481231491501511521531281541551301311561571581331591601611361371381391621401411631431441451461471481491641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981511521992002012022032042052061542072082092101561571581592112122132142152162172182192202212221611621631641652232242252262272282292302312322332342352362372382392402412422432442452462472481702492501721731741751761772512521791801811821831841851861871881891901911921931941951961972532542552562572582592602612622002012632642032652662052062672682692702092712722112122132732742752762772782794 unmodified lines2842852862872882892902912922932942952962302312972982993003012353023033043053063079 unmodified lines3173183192512523203213223232552563243253263273283293302623313322643333342662673353363373383393402722732742752762772783413423433443453462802813473483493503511 unmodified line3533543553563572902912923583593603613623633643653662953673683693702 unmodified lines373374375376304377378306379380381382"""
Custom Handler for FLUX.1-dev (without PuLID)
Custom Handler for FLUX.1-dev FP8 optimized for H100 GPU
This handler enables high-quality image generation using FLUX.1-dev model
on Hugging Face Dedicated Endpoints. It provides better quality than schnell
with 28 inference steps (vs 4 for schnell).
This handler provides high-performance image generation using FLUX.1-dev with
FP8 quantization via torchao, optimized for HuggingFace Dedicated Endpoints.
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 maintenance
Based on Runpod flux-dev-fp8 handler with HuggingFace Endpoint adaptations.
Optimizations 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 overhead
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:
- 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)
- 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:
- A100 80GB: Recommended (full quality, batch processing)
- L40S 48GB: Supported with CPU offload
- A10G 24GB: Supported with aggressive offload
- 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:
- Single prompt: {"inputs": "prompt text", "parameters": {...}}
- Batch prompts: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}
API Format (HuggingFace Standard):
- Single: {"inputs": "prompt text", "parameters": {...}}
- Batch: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}
Response Format:
- Single: {"image": "base64..."}
- Batch: [{"image": "base64..."}, {"image": "base64..."}, ...]
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 parallel
References:
- 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 os
import gc
# Model ID
MODEL_ID = "black-forest-labs/FLUX.1-dev"
# Environment configuration
TORCH_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"))
USE_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-detect
NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))
ENABLE_OFFLOAD = os.environ.get("ENABLE_OFFLOAD", "auto").lower()
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 image
if gpu_memory_gb >= 140: # H200
return 24
elif gpu_memory_gb >= 80: # H100/A100
return 8
elif gpu_memory_gb >= 48: # L40S
return 6
else:
return 4
else:
# BF16: ~24GB model + ~8GB per image
if gpu_memory_gb >= 140: # H200
return 12
elif gpu_memory_gb >= 80: # H100/A100
return 4
elif gpu_memory_gb >= 48: # L40S
return 3
else:
return 2
class EndpointHandler:
def __init__(self, path: str = ""):
"""
Initialize the FLUX.1-dev pipeline with optimizations.
Initialize the FLUX.1-dev pipeline with H100 optimizations.
Optimizations:
- BF16 precision (native Tensor Core support)
- torch.compile with reduce-overhead mode (optional)
- CPU offloading for smaller GPUs
- 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 sizing
Args:
path: Path to model weights (provided by Inference Endpoints)
"""
from diffusers import FluxPipeline
from diffusers import FluxPipeline, FluxTransformer2DModel, TorchAoConfig
# Check for GPU
if 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 info
gpu_props = torch.cuda.get_device_properties(0)
self.gpu_memory_gb = gpu_props.total_memory / 1e9
print(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 memory
if ENABLE_OFFLOAD == "auto":
# A100 80GB (reports ~85GB): no offload needed
# L40S 48GB: use model CPU offload
# A10G 24GB: use sequential CPU offload
self.use_offload = self.gpu_memory_gb < 60
self.use_sequential_offload = self.gpu_memory_gb < 30
elif ENABLE_OFFLOAD == "true":
self.use_offload = True
self.use_sequential_offload = self.gpu_memory_gb < 30
self.compute_capability = gpu_props.major + gpu_props.minor / 10
print(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 = False
else:
self.use_offload = False
self.use_sequential_offload = False
self.use_fp8 = USE_FP8
print(f"[FLUX-Dev] Offload: {self.use_offload}, Sequential: {self.use_sequential_offload}")
# Determine batch size
self.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 model
if path and os.path.exists(os.path.join(path, "model_index.json")):
model_id = path
else:
model_id = "black-forest-labs/FLUX.1-dev"
model_id = MODEL_ID
print(f"[FLUX-Dev] Loading model from: {model_id}")
print(f"[FLUX-FP8] Loading model: {model_id}")
load_start = time.time()
# Get HuggingFace token for gated model access
# HF_TOKEN is automatically set by Inference Endpoints when configured in secrets
hf_token = os.environ.get("HF_TOKEN")
if hf_token:
hf_token = hf_token.strip() # Remove any whitespace
print(f"[FLUX-Dev] Using HF_TOKEN for authentication (length={len(hf_token)}, prefix={hf_token[:4]}...)")
hf_token = hf_token.strip()
print(f"[FLUX-FP8] Using HF_TOKEN for authentication (length={len(hf_token)})")
else:
print("[FLUX-Dev] Warning: HF_TOKEN not set, may fail for gated models")
raise RuntimeError("HF_TOKEN is required for FLUX.1-dev (gated model)")
# Verify token has access to the gated model before loading
if hf_token and model_id == "black-forest-labs/FLUX.1-dev":
if model_id == MODEL_ID:
from huggingface_hub import HfApi
try:
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})")
print(f"[FLUX-FP8] 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(f"[FLUX-FP8] Token verification failed: {e}")
print("[FLUX-FP8] 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")
print(f" 2. You have accepted the license at https://huggingface.co/{model_id}")
raise RuntimeError(f"Cannot access gated model: {e}")
# Load pipeline with BF16
self.pipe = FluxPipeline.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
torch_dtype = torch.bfloat16
token=hf_token, # Required for gated models like FLUX.1-dev
)
# Apply offloading based on GPU memory
if 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()
# 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 = False
self.pipe = FluxPipeline.from_pretrained(
model_id,
torch_dtype=torch_dtype,
token=hf_token,
)
else:
print("[FLUX-Dev] Loading full model to GPU")
self.pipe.to(self.device)
# Load without quantization
print("[FLUX-FP8] Loading pipeline without FP8 quantization (BF16)...")
self.pipe = FluxPipeline.from_pretrained(
model_id,
torch_dtype=torch_dtype,
token=hf_token,
)
print(f"[FLUX-Dev] Model loaded in {time.time() - load_start:.1f}s")
# Enable VAE slicing for memory efficiency
self.pipe.enable_vae_slicing()
print("[FLUX-FP8] VAE slicing enabled")
# Optionally apply torch.compile
if ENABLE_TORCH_COMPILE and not self.use_sequential_offload:
self._apply_torch_compile()
self._run_warmup()
# 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_COMPILE
if self.gpu_memory_gb >= 70: # H100 80GB, H200 141GB
print("[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 hooks
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
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 hooks
print(f"[FLUX-FP8] Model loaded in {time.time() - load_start:.1f}s")
# Apply torch.compile for additional speedup
self._compiled = False
if 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 = True
print("[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 memory
gc.collect()
torch.cuda.empty_cache()
allocated = torch.cuda.memory_allocated() / 1e9
print(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()
print(f"[FLUX-FP8] Ready (compile={self._compiled}, fp8={self.use_fp8}, GPU allocated={allocated:.2f}GB)")
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 stability
self.pipe.transformer = torch.compile(
self.pipe.transformer,
mode=compile_mode,
fullgraph=False,
)
self._compiled = True
print(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 = False
def _run_warmup(self):
"""Run warmup inference to capture CUDA graphs."""
print(f"[FLUX-Dev] Running warmup at 1344x768 (batch_size={FIXED_BATCH_SIZE})...")
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.inference_mode():
warmup_prompts = ["warmup test image"] * FIXED_BATCH_SIZE
with torch.no_grad():
_ = self.pipe(
prompt=warmup_prompts,
prompt="warmup",
num_inference_steps=NUM_INFERENCE_STEPS,
width=1344,
height=768,
width=1536,
height=864,
guidance_scale=3.5,
)
print(f"[FLUX-Dev] Warmup completed in {time.time() - warmup_start:.1f}s")
print(f"[FLUX-FP8] Triton compilation completed in {time.time() - warmup_start:.1f}s")
except Exception as e:
print(f"[FLUX-Dev] Warmup failed: {e}")
self._compiled = False
print("[FLUX-Dev] Falling back to non-compiled mode")
print(f"[FLUX-FP8] Warmup failed: {e}")
import traceback
traceback.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: 1344)
- height: Image height (default: 768)
- width: Image width (default: 1536)
- height: Image height (default: 864)
- seed: Random seed for reproducibility (default: -1, random)
Returns:
Single dict or list of dicts with base64-encoded images
HuggingFace Standard Format:
- Single: {"image": "data:image/png;base64,..."}
- Batch: [{"image": "data:image/png;base64,..."}, ...]
"""
# Extract inputs
inputs = data.get("inputs", data)9 unmodified lines # Extract parameters with FLUX.1-dev defaults
num_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)
width = parameters.get("width", 1536)
height = parameters.get("height", 864)
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}")
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 reproducibility
generator = None
if seed != -1:
generator = torch.Generator(device="cpu").manual_seed(seed)
print(f"[FLUX-Dev] Using seed: {seed}")
print(f"[FLUX-FP8] Using seed: {seed}")
# Process in fixed-size batches
# Process in batches
all_images = []
batch_size = FIXED_BATCH_SIZE if self._compiled else min(len(prompts), FIXED_BATCH_SIZE)
batch_size = self.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")
# Log prompt lengths for debugging
prompt_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()
# Generate images
with torch.inference_mode():
# Use inference_mode for best performance with torchao
with torch.no_grad():
result = self.pipe(
prompt=batch_prompts,
num_inference_steps=num_inference_steps,1 unmodified line height=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[:actual_count])
# Clean up after each batch
all_images.extend(result.images)
batch_time = time.time() - batch_start
time_per_image = batch_time / actual_count
print(f"[FLUX-FP8] Batch {i // batch_size + 1} completed in {batch_time:.1f}s ({time_per_image:.2f}s/image)")
# Cleanup after each batch
self._cleanup_memory()
# Encode images to base64
# Encode images to base64 (HuggingFace standard format)
encoded_results = []
for idx, image in enumerate(all_images):
buffered = BytesIO()2 unmodified lines encoded_results.append({
"image": f"data:image/png;base64,{b64_image}"
})
if (idx + 1) % 10 == 0 or idx == len(all_images) - 1:
print(f"[FLUX-Dev] Encoded image {idx + 1}/{len(all_images)}")
print(f"[FLUX-FP8] Encoded image {idx + 1}/{len(all_images)}")
# Return dict for single input, list for batch
# Return dict for single input, list for batch (HuggingFace standard)
if single_input:
return encoded_results[0]
return encoded_resultshandler.py+228-155