Upload handler.py with huggingface_hub
Browse files73 unmodified lines747576777778798081146 unmodified lines22822923023023123223323423523623723860 unmodified lines2993003012972982993023033043053063073083093103113123133143153163174 unmodified lines32232332432532632732832933033133233333433533673 unmodified lines
# 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)
# NOTE: Created in lifespan() to ensure it's in the correct event loop
inference_semaphore = None
def load_pipeline():146 unmodified lines# FastAPI app
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Load model on startup."""
"""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
60 unmodified lines 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")
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_steps4 unmodified lines 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_starthandler.py+18-5