Upload handler.py with huggingface_hub
Browse files12345234895678911101112131413141515161718192021192223242223242526272829273031323334353236373839343540414243443839454647484344454950475152535455565758594960616263645152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611765666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101191201111121131141221231241251261271281151291301311321331341351361371381391401161421431441451461471481491501171181191201521531541551561571581591601211221231241251261271281291301311321331341621631641351361371381391401411421431441451461471481491501511521531541551561571581591601611661671681691701711621731631641651761771781791801811821831841851661671871681691701711721731741751891901911761771781791931941951961971981991801811821831841851861871881891901911921931941951961971981992002012022012022032032042052062072082092102112122132142152162172182192202212222232242252052062072262092102112122132142152162172182192202212222232242252262272282292272282292302312322332312322332342342362372382392402352362372382392402412422422432442452462472482442452462472482492502512522532502542522532542552562572582592602612622632642652662672682692702712722552562572582742752762772592792802812822832842852862872882892902912922932942952962972982602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323013333343033043353363373383393403412 unmodified lines344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393314315316317318319320321322323324325326327328329330331332333334335336337394395396397398399400401402403404405406407408409410339340411412413414415416343344345346347348349350351352353354355356357358359360361362363364365366367368369370371417373418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451"""
FLUX.2-dev Handler for HuggingFace Dedicated Endpoints
This handler uses REMOTE TEXT ENCODING to avoid loading the Mistral3 text encoder locally.
This allows running on HuggingFace Inference Endpoints with PyTorch 2.2.0.
FLUX.2-dev FastAPI Handler for HuggingFace Dedicated Endpoints (Custom Container)
Features:
- Remote text encoding via HuggingFace API (saves ~24GB VRAM)
- BF16 precision for transformer
- 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)
- 1920x1080 output resolution
- 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 Modes:
- generate: Normal text-to-image generation
- generate_with_refs: Multi-reference image generation with character/style consistency
API Endpoints:
- POST /: Generate image(s) (HF Endpoints standard format)
- GET /health: Health check
- GET /info: Model information
Input format:
{
"inputs": "prompt text",
"inputs": "prompt text" or ["prompt1", "prompt2", ...],
"parameters": {
"mode": "generate" | "generate_with_refs",
"reference_images": ["base64...", ...], # For generate_with_refs
"width": 1920,
"height": 1080,
"reference_images": ["base64...", ...],
"width": 1536,
"height": 864,
"num_inference_steps": 50,
"guidance_scale": 4.0,
"seed": -1
"seed": -1,
"output_format": "jpeg" | "png"
}
}
Environment Variables:
- HF_TOKEN: HuggingFace token for model and remote text encoder access (REQUIRED)
- 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)
Note: Remote text encoding requires a valid HuggingFace token.
- 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)
"""
from typing import Dict, List, Any, Union, Optional
import torch
import os
import gc
import time
import base64
import os
import io
import requests
import asyncio
from io import BytesIO
from PIL import Image
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
# Environment configuration
# 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"))
DEFAULT_WIDTH = 1920
DEFAULT_HEIGHT = 1080
REMOTE_TEXT_ENCODER_URL = "https://remote-text-encoder-flux-2.huggingface.co/predict"
class EndpointHandler:
"""HuggingFace Dedicated Endpoint Handler for FLUX.2-dev with Remote Text Encoding."""
def __init__(self, path: str = ""):
"""Initialize FLUX.2-dev pipeline with remote text encoding."""
if not torch.cuda.is_available():
raise RuntimeError("GPU is required for FLUX.2-dev inference")
self.device = torch.device("cuda")
self.hf_token = os.environ.get("HF_TOKEN", "")
if not self.hf_token:
raise RuntimeError("HF_TOKEN is required for remote text encoding")
# 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}")
print(f"[FLUX2] Using REMOTE TEXT ENCODING (saves ~24GB VRAM)")
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 _remote_encode_prompt(self, prompt: str) -> torch.Tensor:
"""Encode prompt using remote text encoder API."""
try:
response = requests.post(
REMOTE_TEXT_ENCODER_URL,
json={"prompt": prompt},
headers={
"Authorization": f"Bearer {self.hf_token}",
"Content-Type": "application/json"
},
timeout=60
)
if response.status_code != 200:
raise RuntimeError(f"Remote text encoder failed: {response.status_code} - {response.text}")
# Load the tensor from response
embeddings = torch.load(io.BytesIO(response.content), weights_only=False)
return embeddings.to(self.device)
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Remote text encoder request failed: {e}")
def _setup_pipeline(self):
"""Setup FLUX.2-dev pipeline with remote text encoding."""
print("[FLUX2] Setting up pipeline with remote text encoding...")
load_start = time.time()
self._log_gpu_memory("before_setup")
# Import diffusers components
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
inference_semaphore = asyncio.Semaphore(1)
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 Flux2Pipeline, Flux2Transformer2DModel, AutoencoderKLFlux2
print("[FLUX2] Using Flux2Pipeline (diffusers)")
from diffusers import FluxPipeline as Flux2Pipeline
from diffusers import FluxTransformer2DModel as Flux2Transformer2DModel
print("[FLUX2] Using FluxPipeline fallback (diffusers)")
except ImportError:
try:
from diffusers import FluxPipeline as Flux2Pipeline
from diffusers import FluxTransformer2DModel as Flux2Transformer2DModel
from diffusers import AutoencoderKL as AutoencoderKLFlux2
print("[FLUX2] Using FluxPipeline fallback (diffusers)")
except ImportError:
raise RuntimeError("diffusers does not support FLUX.2 yet. Please update diffusers.")
raise RuntimeError("diffusers does not support FLUX.2 yet")
model_id = "black-forest-labs/FLUX.2-dev"
# Load transformer (main diffusion model)
print("[FLUX2] Loading transformer...")
self.transformer = Flux2Transformer2DModel.from_pretrained(
model_id,
subfolder="transformer",
torch_dtype=torch.bfloat16,
token=self.hf_token,
)
print("[FLUX2] Transformer loaded")
# Load VAE
print("[FLUX2] Loading VAE...")
self.vae = AutoencoderKLFlux2.from_pretrained(
model_id,
subfolder="vae",
torch_dtype=torch.bfloat16,
token=self.hf_token,
)
print("[FLUX2] VAE loaded")
# Load with FP8 quantization
fp8_applied = False
quantization_type = "none"
self._log_gpu_memory("after_model_load")
# Load scheduler
from diffusers import FlowMatchEulerDiscreteScheduler
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
model_id,
subfolder="scheduler",
token=self.hf_token,
)
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,
)
# Create pipeline without text encoder (we'll use remote encoding)
# Note: We need to handle this differently since Flux2Pipeline expects text encoder
self.pipe = Flux2Pipeline.from_pretrained(
# 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,
transformer=self.transformer,
vae=self.vae,
text_encoder=None, # Skip text encoder
text_encoder_2=None, # Skip second text encoder if any
tokenizer=None,
tokenizer_2=None,
torch_dtype=torch.bfloat16,
token=self.hf_token,
token=HF_TOKEN,
)
# Store reference for remote encoding
self.use_remote_encoding = True
# Move to GPU
if self.gpu_memory_gb >= 40:
print("[FLUX2] Loading model to GPU")
self.pipe.to(self.device)
else:
print("[FLUX2] Using model CPU offload (limited VRAM)")
self.pipe.enable_model_cpu_offload()
print(f"[FLUX2] Quantization status: fp8_applied={fp8_applied}, type={quantization_type}")
self._log_gpu_memory("after_device_setup")
# 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()
# Warmup with remote encoding
print("[FLUX2] Running warmup with remote text encoding...")
warmup_start = time.time()
# Apply torch.compile to transformer
if USE_COMPILE:
print("[FLUX2] Applying torch.compile to transformer...")
try:
# Test remote text encoder
print("[FLUX2] Testing remote text encoder...")
test_embeds = self._remote_encode_prompt("warmup test")
print(f"[FLUX2] Remote encoder OK, embedding shape: {test_embeds.shape}")
warmup_time = time.time() - warmup_start
print(f"[FLUX2] Warmup completed in {warmup_time:.1f}s")
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()
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}",
}
# 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}"
# FastAPI app
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Load model on startup."""
load_pipeline()
yield
def _generate(self, data: Dict) -> Dict:
"""Normal text-to-image generation with remote text encoding."""
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)
app = FastAPI(title="FLUX.2-dev API", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
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}")
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
start_time = time.time()
try:
# Get text embeddings from remote encoder
print("[FLUX2] Getting text embeddings from remote encoder...")
prompt_embeds = self._remote_encode_prompt(prompt)
with torch.inference_mode():
result = self.pipe(
prompt_embeds=prompt_embeds,
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()
class GenerateRequest(BaseModel):
inputs: Union[str, List[str]]
parameters: Optional[GenerateParameters] = None
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
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
if pipe is None:
raise HTTPException(status_code=503, detail="Model not loaded")
# Normalize inputs to list
prompts = [request.inputs] if isinstance(request.inputs, str) else request.inputs
params = request.parameters or GenerateParameters()
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)
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")
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 = self._decode_images(ref_images_b64)
ref_images = 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}")
# 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 = None2 unmodified lines 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}")
try:
# Get text embeddings from remote encoder
print("[FLUX2] Getting text embeddings from remote encoder...")
prompt_embeds = self._remote_encode_prompt(prompt)
with torch.inference_mode():
# FLUX.2 multi-reference: pass images via 'image' parameter
result = self.pipe(
prompt_embeds=prompt_embeds,
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()
# 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": self._encode_image(result.images[0]),
"generation_time_seconds": generation_time,
"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,
}
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) 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_infohandler.py+387-309