File size: 17,419 Bytes
5e02dae 5525ec8 34a74f8 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 a5af71c 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 34a74f8 5525ec8 5e02dae 5525ec8 34a74f8 5525ec8 34a74f8 5525ec8 34a74f8 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 a5af71c 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 a5af71c 5525ec8 a5af71c 5525ec8 a5af71c 5525ec8 a5af71c 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 5e02dae 5525ec8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | """
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
@asynccontextmanager
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}"
@app.post("/")
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()
@app.get("/health")
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(),
}
@app.get("/info")
async def info():
"""Get model information."""
return model_info
|