Download handler.py from kkytai/flux2-dev-handler: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/kkytai/flux2-dev-handler/resolve/main/handler.py
- Command line
-
hf download hf://kkytai/flux2-dev-handler/handler.py
-
curl -L -o handler.py https://huggingface.co/kkytai/flux2-dev-handler/resolve/main/handler.py
17.4 kB
| """ | |
| 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 support | |
| API Endpoints: | |
| - POST /: Generate image(s) (HF Endpoints standard format) | |
| - GET /health: Health check | |
| - GET /info: Model information | |
| Input 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 os | |
| import gc | |
| import time | |
| import base64 | |
| import asyncio | |
| from io import BytesIO | |
| from typing import Dict, List, Any, Union, Optional | |
| from contextlib import asynccontextmanager | |
| import torch | |
| from PIL import Image | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| # Configuration | |
| HF_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 = 1536 | |
| DEFAULT_HEIGHT = 864 # 16の倍数、16:9 | |
| DEFAULT_OUTPUT_FORMAT = os.environ.get("DEFAULT_OUTPUT_FORMAT", "jpeg").lower() # jpeg or png | |
| INFERENCE_TIMEOUT = int(os.environ.get("INFERENCE_TIMEOUT", "120")) # Max wait time for semaphore | |
| # Global state | |
| pipe = None | |
| model_info = {} | |
| # Semaphore to limit concurrent GPU inference (1 at a time per instance) | |
| # Other requests wait in queue, enabling autoscaling across multiple instances | |
| # NOTE: Created in lifespan() to ensure it's in the correct event loop | |
| inference_semaphore = None | |
| def load_pipeline(): | |
| """Load FLUX.2-dev pipeline with FP8 quantization and torch.compile.""" | |
| global pipe, model_info | |
| if 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 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| print("[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 / 1e9 | |
| print(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, Flux2Transformer2DModel | |
| print("[FLUX2] Using Flux2Pipeline (diffusers)") | |
| except ImportError: | |
| try: | |
| from diffusers import FluxPipeline as Flux2Pipeline | |
| from diffusers import FluxTransformer2DModel as Flux2Transformer2DModel | |
| print("[FLUX2] Using FluxPipeline fallback (diffusers)") | |
| except ImportError: | |
| raise RuntimeError("diffusers does not support FLUX.2 yet") | |
| # Load with FP8 quantization | |
| fp8_applied = False | |
| quantization_type = "none" | |
| if USE_FP8: | |
| print("[FLUX2] Loading transformer with FP8 quantization...") | |
| 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, | |
| ) | |
| # Verify FP8 was actually applied | |
| fp8_applied = True | |
| quantization_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 GPU | |
| if 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 transformer | |
| if 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 cache | |
| warmup_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_start | |
| print(f"[FLUX2] Warmup completed in {warmup_time:.1f}s") | |
| except Exception as e: | |
| print(f"[FLUX2] Warmup failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| # Cleanup | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| load_time = time.time() - load_start | |
| print(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 | |
| async def lifespan(app: FastAPI): | |
| """Load model on startup and initialize semaphore in correct event loop.""" | |
| global inference_semaphore | |
| # Create semaphore in the running event loop (not at module load time) | |
| inference_semaphore = asyncio.Semaphore(1) | |
| print(f"[FLUX2] Inference semaphore initialized (timeout={INFERENCE_TIMEOUT}s)") | |
| load_pipeline() | |
| yield | |
| app = 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]] = None | |
| width: 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 png | |
| class GenerateRequest(BaseModel): | |
| inputs: Union[str, List[str]] | |
| parameters: Optional[GenerateParameters] = None | |
| def 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 result | |
| def 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 encoding | |
| if 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}" | |
| 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 pipe | |
| import sys | |
| # Normalize inputs to list | |
| prompts = [request.inputs] if isinstance(request.inputs, str) else request.inputs | |
| params = request.parameters or GenerateParameters() | |
| # Log request received immediately (flush to ensure visibility before potential crash) | |
| print(f"[FLUX2] Request received: {len(prompts)} prompt(s)") | |
| sys.stdout.flush() | |
| if pipe is None: | |
| raise HTTPException(status_code=503, detail="Model not loaded") | |
| width = params.width | |
| height = params.height | |
| num_steps = params.num_inference_steps | |
| guidance = params.guidance_scale | |
| seed = params.seed | |
| mode = params.mode | |
| output_format = params.output_format | |
| ref_images_b64 = params.reference_images or [] | |
| # Wait for semaphore (queue for GPU access) | |
| print(f"[FLUX2] Waiting for semaphore...") | |
| sys.stdout.flush() | |
| queue_start = time.time() | |
| try: | |
| await asyncio.wait_for(inference_semaphore.acquire(), timeout=INFERENCE_TIMEOUT) | |
| except asyncio.TimeoutError: | |
| queue_time = time.time() - queue_start | |
| print(f"[FLUX2] Request timed out after {queue_time:.1f}s waiting for GPU") | |
| sys.stdout.flush() | |
| raise HTTPException(status_code=503, detail=f"Server busy, timed out after {INFERENCE_TIMEOUT}s") | |
| queue_time = time.time() - queue_start | |
| if 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 provided | |
| ref_images = None | |
| if ref_images_b64: | |
| ref_images = decode_images(ref_images_b64) | |
| print(f"[FLUX2] Using {len(ref_images)} reference image(s)") | |
| # Lower guidance for reference mode | |
| if guidance > 2.5: | |
| guidance = 2.5 | |
| print(f"[FLUX2] Guidance scale capped to {guidance} for reference mode") | |
| # 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() | |
| all_images = [] | |
| total_inference_time = 0.0 | |
| total_encode_time = 0.0 | |
| total_gc_time = 0.0 | |
| # Process in batches | |
| for i in range(0, len(prompts), BATCH_SIZE): | |
| batch_prompts = prompts[i:i + BATCH_SIZE] | |
| batch_num = i // BATCH_SIZE + 1 | |
| total_batches = (len(prompts) + BATCH_SIZE - 1) // BATCH_SIZE | |
| print(f"[FLUX2][BATCH {batch_num}] prompts={len(batch_prompts)}") | |
| # Inference | |
| inference_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_start | |
| total_inference_time += inference_time | |
| print(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 images | |
| encode_start = time.time() | |
| encoded_images = [encode_image(img, output_format) for img in all_images] | |
| encode_time = time.time() - encode_start | |
| total_encode_time = encode_time | |
| print(f"[FLUX2][ENCODE] encode_time={encode_time:.1f}s ({encode_time/len(all_images):.2f}s/img) format={output_format}") | |
| # Cleanup | |
| gc_start = time.time() | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| gc_time = time.time() - gc_start | |
| total_gc_time = gc_time | |
| print(f"[FLUX2][GC] gc_time={gc_time:.2f}s") | |
| # Summary | |
| total_time = time.time() - start_time | |
| print(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 input | |
| if 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 traceback | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| finally: | |
| # Always release semaphore to allow next request | |
| inference_semaphore.release() | |
| 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(), | |
| } | |
| async def info(): | |
| """Get model information.""" | |
| return model_info | |