Add FLUX.2-dev handler
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365"""
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 resolution
API Modes:
- generate: Normal text-to-image generation
- generate_with_refs: Multi-reference image generation with character/style consistency
Input 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 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, Optional
import torch
import gc
import time
import base64
import os
from io import BytesIO
from PIL import Image
# Environment configuration
NUM_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 = 1920
DEFAULT_HEIGHT = 1080
class 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 info
gpu_props = torch.cuda.get_device_properties(0)
self.gpu_memory_gb = gpu_props.total_memory / 1e9
print(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()
def _log_gpu_memory(self, stage: str):
"""Log GPU memory usage."""
if torch.cuda.is_available():
allocated = torch.cuda.memory_allocated() / 1e9
reserved = torch.cuda.memory_reserved() / 1e9
print(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 ID
try:
from diffusers import FluxPipeline as Flux2Pipeline
from diffusers import FluxTransformer2DModel as Flux2Transformer2DModel
print("[FLUX2] Using FluxPipeline (diffusers)")
except ImportError:
# Fallback if Flux2-specific classes exist
try:
from diffusers import Flux2Pipeline, Flux2Transformer2DModel
print("[FLUX2] Using Flux2Pipeline (diffusers)")
except ImportError:
raise RuntimeError("diffusers does not support FLUX.2 yet. Please update diffusers.")
# Get HF token
hf_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 path
model_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 / 10
use_fp8 = USE_FP8 and compute_cap >= 8.9
if 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 supported
if use_fp8:
print("[FLUX2] Loading with FP8 quantization (torchao)...")
try:
from diffusers import TorchAoConfig
quantization_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 model
if 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)")
self.pipe.enable_model_cpu_offload()
self._log_gpu_memory("after_device_setup")
# Apply torch.compile for speedup
if 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")
# Warmup
print("[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_start
print(f"[FLUX2] Warmup completed in {warmup_time:.1f}s")
except Exception as e:
print(f"[FLUX2] Warmup failed: {e}")
# Cleanup
gc.collect()
torch.cuda.empty_cache()
load_time = time.time() - load_start
print(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 result
def _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."""
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 reproducibility
generator = None
if seed != -1:
generator = torch.Generator(device="cpu").manual_seed(seed)
print(f"[FLUX2] Using seed: {seed}")
start_time = time.time()
try:
with torch.inference_mode():
result = self.pipe(
prompt=prompt,
width=width,
height=height,
num_inference_steps=num_steps,
guidance_scale=guidance,
generator=generator,
)
generation_time = time.time() - start_time
print(f"[FLUX2] Generated in {generation_time:.1f}s")
# Cleanup
gc.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 traceback
traceback.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 images
ref_images = None
if 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 reproducibility
generator = None
if seed != -1:
generator = torch.Generator(device="cpu").manual_seed(seed)
print(f"[FLUX2] Using seed: {seed}")
start_time = time.time()
try:
with torch.inference_mode():
# FLUX.2 multi-reference: pass images via 'image' parameter
result = self.pipe(
prompt=prompt,
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_time
print(f"[FLUX2] Generated with refs in {generation_time:.1f}s")
# Cleanup
gc.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 traceback
traceback.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)handler.pyAdded+365