waveshaker's picture
Update README.md
6771d48 verified
|
Raw History Blame Contribute Delete
9.8 kB

A newer version of the Gradio SDK is available: 6.32.0

Upgrade
metadata
title: Universal Model Character LoRA Studio
emoji: ๐ŸŽจ
colorFrom: gray
colorTo: green
sdk: gradio
hf_oauth: true
fullWidth: true
sdk_version: 6.31.0
python_version: '3.12'
app_file: app.py
pinned: true
short_description: Run waveshaker's ๐— ๐—ข๐—ฆ๐—ฆ/๐—ž๐—ฟ๐—ฒ๐—ฎ๐Ÿฎ/๐—”๐—ป๐—ถ๐—บ๐—ฎ/๐—™๐—Ÿ๐—จ๐—ซ/๐—ฃ๐—ผ๐—ป๐˜† LoRAs

โšก Universal LoRA Studio


โš™๏ธ System Architecture

This Space is a specialized, on-demand inference engine designed to run Waveshaker's character LoRAs on ZeroGPU. To overcome Hugging Face's cross-space CORS restrictions and ZeroGPU's billing constraints, I use a decoupled "Proxy-Driven" architecture with a blazing-fast native frontend.

๐Ÿ—๏ธ System Topology

Layer Role & Responsibility
๐Ÿ–ฅ Client Layer Handles OAuth authentication, renders the UI, manages background file pre-warming, and submits payload parameters.
๐Ÿง  Proxy & Scheduler Layer
(FastAPI + Gradio)
Manages scanner bypasses, executes model pre-warming, serializes tasks, and enforces system limits.
โšก Execution Layer
(ZeroGPU + ComfyUI)
Utilizes native SafeTensors loading with Linux Page Cache acceleration, leverages ComfyUI's native cache for model hot-swapping, and outputs WebP images with EXIF metadata.

๐Ÿ”„ Request Lifecycle

[User] โ”€โ”€(OAuth Login)โ”€โ”€โ–บ [Native Studio UI]
                               โ”‚
                               โ”‚ (POST `/api/warmup` & `/api/generate`)
                               โ–ผ
                 [FastAPI Gateway & Daemon Scheduler]
                 โ”œโ”€โ”€ Input Validation (Enforces 1536px & steps limit)
                 โ”œโ”€โ”€ ContextVar (Binds task_id & x-ip-token)
                 โ””โ”€โ”€ Native Daemon Thread (Decouples HTTP response)
                               โ”‚
         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
         โ–ผ (Parallel Page-Cache Preload)             โ–ผ (On-Demand Prep)
[WarmupManager State Machine]               [Background Worker & Env Prep]
โ”œโ”€โ”€ P0 Preemption & posix_fadvise             โ”œโ”€โ”€ On-demand LoRA download
โ”œโ”€โ”€ Yield to _gen_inflight I/O                โ””โ”€โ”€ Model switch lock (_model_switch_lock)
โ””โ”€โ”€ Syncs /tmp/warmup_state.json                       โ”‚
                                                       โ”‚ (Requests GPU slice)
                                                       โ–ผ
                                    [Gradio + ZeroGPU (@spaces.GPU duration=90)]
                                    โ”œโ”€โ”€ Dummy Probe (Retains quota & allocates slot)
                                    โ”œโ”€โ”€ _warm_wait_in_gpu (Smart wait if progress โ‰ฅ90%)
                                    โ””โ”€โ”€ Threading Lock (Serializes jobs via _exec_lock)
                                                       โ”‚
                                                       โ”‚ (Passes to Singleton Executor)
                                                       โ–ผ
                                            [ComfyUI Core Engine]
                                            โ”œโ”€โ”€ Loader Chain Cache (Stable node IDs)
                                            โ”œโ”€โ”€ RAM_PRESSURE Cache (lru=8, ram=16GB)
                                            โ””โ”€โ”€ UnifiedProgressTqdm (Live step metrics)
                                                       โ”‚
                                                       โ”‚ (Outputs raw PNG)
                                                       โ–ผ
                                         [Pillow Post-Processing & Re-warm]
                                         โ”œโ”€โ”€ WebP (Q90) + Binary EXIF Metadata Injection
                                         โ””โ”€โ”€ Post-Gen Re-warm (Triggers WILLNEED)
                                                       โ”‚
                                                       โ–ผ
                                         [Static `/output/` Mount] โ”€โ”€โ–บ [Browser Renders Image]

๐Ÿ“ One-Sentence Summary

A decoupled "Proxy-Driven" architecture: a native frontend passes LoRA parameters via URL, while a Gradio proxy bypasses cross-space CORS and ZeroGPU billing constraints. It serves generated images as physical WebP URLs with custom-injected ComfyUI EXIF metadata, delivering accurate billing.

๐Ÿ“œ Architecture Evolution

  • v0.1 (The FastAPI Initiation): The initial dual-track setup. FastAPI handled data routing, while Gradio rendered the UI. Due to cross-space CORS restrictions and a lack of x-ip-token handling, the frontend fell into the ZeroGPU anonymous pool.
  • v0.2 (The Gradio-Injection Era): A modular reconstruction (core/, frontend/, ui/). Introduced the task_runner for precise background scheduling and logging. To retain ZeroGPU billing, I hid Gradio components and injected native HTML/CSS/JS via Python. This successfully kept the GPU quota but introduced frontend performance bottlenecks and UI state sync issues.
  • v0.3 (The Decoupled Proxy UI): A new refactor. A 100% native static web UI is decoupled from the FastAPI backend. I implemented a dummy Gradio probe to trick the ZeroGPU scanner and used ContextVar to perfectly pass through the x-ip-token. Featuring a dual-Space sync mechanism (frontend_cache), it delivers faster loading,accurate ZeroGPU billing, and a pure native frontend experience.
  • v0.4 (The Performance Hardened Era): A brutal optimization phase to eliminate the 50s+ cold-start latency and multi-model memory leaks under ZeroGPU.
    • Binary Tensor Fast-Path: Bypassed ComfyUI's native slow loading path by intercepting load_torch_file and implementing numpy zero-copy for large INT8/ConvRot tensors.
    • Lazy Execution & Native Cache: Removed aggressive empty_cache and manual GC interventions. Relied entirely on ComfyUI's native RAM_PRESSURE (LRU 8, 16GB RAM limit) to orchestrate multi-model hot-swapping smoothly.
    • Queue-Aware Billing: Adjusted @spaces.GPU(duration=40) to gracefully handle ZeroGPU queueing spikes during consecutive architecture switching.
    • Safety Boundaries: Enforced hard pixel and edge limits (1536px) at both frontend and FastAPI levels to prevent OOM and timeout kills.
    • Result: Cold-start load time dropped from 24s to **6.5s**. Cross-architecture hot-swapping (e.g., Flux 1536 โ†’ MOSS 1536) stabilized under 15s total, completely eliminating the "ghost 35s" timeouts.
  • v0.5 (The Zero-Cost Warmup & Concurrency Hardened Era): Eliminated disk cold-read bottlenecks without burning a single second of ZeroGPU quota, while hardening full-stack state synchronization.
    • Page-Cache Warmup State Machine (WarmupManager): Implemented a pure CPU/IO file pre-warming engine using os.posix_fadvise(WILLNEED) and chunked sequential reads. Features dynamic cgroup v1/v2 memory budget awareness (60% limit - anon), random 32MB read-speed verification (>= 600 MB/s), and priority preemption (P0 user selection interrupts P1 boot sweep).
    • Tiered & Zero-GPU-Waste Scheduling: Added a 3-tier frontend-backend warmup handshake (lite 200MB header read on page entry โ†’ full model preload on selection โ†’ 10-min touch heartbeat). In-GPU residual waits (WARMUP_RESIDUAL_WAIT = 5.0s) automatically abort early if warmup progress < 90%, avoiding idle GPU quota burn.
    • Stable Loader Chain & Progress Interception: Locked loader node IDs (1..N) to maximize ComfyUI RAM_PRESSURE node-cache hits. Replaced tqdm with a re-entrant ref-counted monkey-patch bound to ContextVar and atomic /tmp metric dumps (os.replace) for flicker-free step/load telemetry.
    • Quota Ceiling & Resilience: Raised @spaces.GPU(duration=90) (ceiling, not billed) to protect cold-start model loading from premature timeouts. Added exponential backoff retries, config background healing, and deep-link (?model=&lora=) image prefetching on the frontend.
  • v0.6 (The Targeted Preload & Zero-Stall Polish): Eliminated background I/O thrashing, state-file race conditions, and self-preemption bottlenecks discovered during real-world multi-model stress testing. Targeted On-Demand Preloading: Disabled blind full-repository boot sweeps (boot_sweep) and background task resurrection (_resume). Restricted background disk reads strictly to the active/selected model, preventing idle models (e.g., MOSS) from evicting the user's current target (e.g., Krea2) out of the Linux Page Cache. Zero-Stall GPU Entry: Removed the in-GPU residual wait (_warm_wait_in_gpu) to eliminate a 5.0s quota-burning stall caused by background sweep tasks overwriting the global warmup state file (target="__sweep__"). GPU slices now begin execution with 0ms delay upon allocation. Same-Target Preload Coalescing: Added active-plan deduplication in WarmupManager.request() so rapid select โ†’ submit transitions coalesce seamlessly and inherit the generation task_id without resetting active file reads. Tightened Quota Ceiling: Re-tuned @spaces.GPU(duration=40) to improve ZeroGPU queue scheduling priority while maintaining full cold-start headroom.

๐Ÿ”— Ecosystem Links

Engineered by waveshaker. Running on ZeroGPU. Duplicated and modified from 2i/pornmaster-krea2.