scriptviz-flux-dev / handler.py
i8i-ky's picture
Update default resolution to 1536x864
d55705b verified
Raw History Blame Contribute Delete
16.1 kB
"""
Custom Handler for FLUX.1-dev FP8 optimized for H100 GPU
This handler provides high-performance image generation using FLUX.1-dev with
FP8 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 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, Union
import torch
from io import BytesIO
import base64
import time
import os
import gc
# Model ID
MODEL_ID = "black-forest-labs/FLUX.1-dev"
# Environment configuration
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"))
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 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 sizing
Args:
path: Path to model weights (provided by Inference Endpoints)
"""
from diffusers import FluxPipeline, FluxTransformer2DModel, TorchAoConfig
if 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 / 1e9
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_fp8 = USE_FP8
# 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 = MODEL_ID
print(f"[FLUX-FP8] Loading model: {model_id}")
load_start = time.time()
# Get HuggingFace token for gated model access
hf_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 loading
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-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 = False
self.pipe = FluxPipeline.from_pretrained(
model_id,
torch_dtype=torch_dtype,
token=hf_token,
)
else:
# 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,
)
# Enable VAE slicing for memory efficiency
self.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_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:
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-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 traceback
traceback.print_exc()
print("[FLUX-FP8] Will retry compilation on first request")
def _cleanup_memory(self):
"""Clean up GPU memory."""
gc.collect()
torch.cuda.empty_cache()
def __call__(self, data: Dict[str, Any]) -> Union[Dict[str, str], List[Dict[str, str]]]:
"""
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 inputs
inputs = data.get("inputs", data)
parameters = data.get("parameters", {})
# Normalize inputs to list
single_input = isinstance(inputs, str)
if single_input:
prompts = [inputs]
else:
prompts = inputs
# 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", 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 reproducibility
generator = None
if seed != -1:
generator = torch.Generator(device="cpu").manual_seed(seed)
print(f"[FLUX-FP8] Using seed: {seed}")
# Process in batches
all_images = []
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)
# 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()
# Use inference_mode for best performance with torchao
with torch.no_grad():
result = self.pipe(
prompt=batch_prompts,
num_inference_steps=num_inference_steps,
width=width,
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)
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 (HuggingFace standard format)
encoded_results = []
for idx, image in enumerate(all_images):
buffered = BytesIO()
image.save(buffered, format="PNG")
b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
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-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